我有一个实现,其中父组件希望通过使用子组件中提供的@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() { }
}发布于 2017-02-26 09:09:42
您可以使用( )运算符,如下所示
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'
}
}发布于 2016-09-27 14:23:49
默认情况下,输入值是可选的。只有当您的代码试图访问未实际传递的输入的属性时(因为这些输入是undefined),代码才会失败。
您可以实现OnChanges或将输入设置为setter而不是属性,以便在实际传递值时执行代码。
export class child {
@Input set showName(value: boolean) {
this._showName = value;
doSomethingWhenShowNameIsPassed(value);
}
constructor() { }
}发布于 2016-09-27 14:24:04
这里有两个选项。
1)以防该子节点输入为空时不需要显示,可以对子节点使用*ngIf。
<parent>
<child *ngIf="true" [showName]="true"></child> //passing parameter
<child></child> //not willing to passing any parameter
</parent>2)以防孩子在没有任何输入的情况下显示,您可以使用修改的setter来检查是否存在输入变量`
在child.ts中:
private _optionalObject: any;
@Input()
set optionalObject(optionalObject: any) {
if(optionalObject) this._optionalObject = optionalObject;
}
get optionalObject() { return this._optionalObject; }https://stackoverflow.com/questions/39717083
复制相似问题