Angular 2:组件交互,可选输入参数
我有一个实现,其中父母想通过使用子组件可用的@Input
参数将某些数据传递给子组件。但是,此数据传输是可选项,父项可能会或可能不会按照要求传递它。是否有可能在组件中有可选的输入参数。我描述了以下情况:Angular 2:组件交互,可选输入参数
<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() { }
}
检查@ galvan的评论,这似乎是一个更好的解决方案。 –
你为什么认为它更好?当父节点必须向服务器发出请求并且仅将该值传递给子节点时,那么在调用'ngAfterViewInit()'之后可能会相当长一段时间。 'ngAfterViewInit()'可能适用于你的具体情况,但总的来说我不会推荐它。 –
你的意思是说,如果我正在改变客户端上的值?正如你所解释的,我应该在子指令中调用setter方法吗? –
您有两种选择。
1)您可以在儿童上使用*ngIf
,以防儿童在输入为空时不需要显示。
<parent>
<child *ngIf="true" [showName]="true"></child> //passing parameter
<child></child> //not willing to passing any parameter
</parent>
2)如果孩子应该得到显示没有任何输入,您可以使用修改后的二传手检查输入的存在variables`
在child.ts:
private _optionalObject: any;
@Input()
set optionalObject(optionalObject: any) {
if(optionalObject) this._optionalObject = optionalObject;
}
get optionalObject() { return this._optionalObject; }
检查@ galvan的评论,这似乎是一个更好的解决方案。 –
是的,你可以有可选的输入,在ngAfterViewInit生命周期事件检查输入初始化或不 – galvan
感谢@galvan,它成功了! –