我有一个实现,其中父希望通过使用子组件中可用的 @Input
参数将某些数据传递给子组件。但是,此数据传输是可选的,父级可能会也可能不会根据要求传递它。组件中是否可以有可选的输入参数。我在下面描述了一个场景:
<parent>
<child [showName]="true"></child> //passing parameter
<child></child> //not willing to passing any parameter
</parent>
//child component definition
@Component {
selector:'app-child',
template:`<h1>Hi Children!</h1>
<span *ngIf="showName">Alex!</span>`
}
export class child {
@Input showName: boolean;
constructor() { }
}
您可以使用 ( ? ) 运算符,如下所示
import {Component,Input} from '@angular/core';
@Component({
selector:'child',
template:`<h1>Hi Children!</h1>
<span *ngIf="showName">Alex!</span>`
})
export class ChildComponent {
@Input() showName?: boolean;
constructor() { }
}
使用子组件的父组件将是
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<child [showName]="true"></child>
<child ></child>
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = 'Angular2'
}
}
默认情况下,输入值是可选的。仅当您的代码尝试访问未实际传递的输入的属性时(因为这些输入是 undefined
),您的代码才会失败。
您可以实现 OnChanges 或将输入设为 setter 而不是属性,以便在实际传递值时执行您的代码。
export class child {
@Input set showName(value: boolean) {
this._showName = value;
doSomethingWhenShowNameIsPassed(value);
}
constructor() { }
}
ngAfterViewInit()
之后的相当长的一段时间。 ngAfterViewInit()
可能适用于您的具体情况,但总的来说我不会推荐它。
<child [showName]="propOnParent">
并且在某些异步调用完成后初始化了 propOnParent
,则 Angular 会更新 <child>
中的 showName
输入,或者如果它是 setter,则调用具有更新值的设置器。
true
等静态绑定值,则 ngOnInit()
是比 ngAfterViewChecked()
更常见的生命周期挂钩。
您在这里有两个选择。
1)您可以在孩子上使用*ngIf
,以防孩子在其输入为空时不需要显示。
<parent>
<child *ngIf="true" [showName]="true"></child> //passing parameter
<child></child> //not willing to passing any parameter
</parent>
2)如果孩子应该在没有任何输入的情况下显示,您可以使用修改后的设置器来检查输入变量的存在`
在 child.ts 中:
private _optionalObject: any;
@Input()
set optionalObject(optionalObject: any) {
if(optionalObject) this._optionalObject = optionalObject;
}
get optionalObject() { return this._optionalObject; }
@Input() showName?: boolean = true;
@Input() showName: boolean;
有什么区别吗?然后检查是否不为空?我的意思是-有什么区别?