我有一个实现,其中父级希望通过使用子组件可用的 @Input
参数将某些数据传递给子组件。但是,此数据传输是可选的, parent 可能会或可能不会根据要求传递它。组件中是否可以有可选的输入参数。我在下面描述了一个场景:
<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'
}
}
关于Angular 2 : Component Interaction, 可选输入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39717083/