角度2:组件交互,可选输入参数 [英] Angular 2: Component Interaction, optional input parameters
本文介绍了角度2:组件交互,可选输入参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个实现,其中父级希望通过使用子级组件上可用的@Input
参数将某些数据传递给子级组件.但是,此数据传输是可选的,并且父级可以按照要求通过也可以不通过.组件中是否可以有可选的输入参数.我在下面描述了一种情况:
I have an implementation where parent wants to pass certain data to child component via the use of @Input
parameter available at the child component. However, this data transfer is a optional thing and the parent may or may not pass it as per the requirement. Is it possible to have optional input parameters in a component. I have described a scenario below:
<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() { }
}
推荐答案
您可以按以下方式使用(?)运算符
You can use the ( ? ) operator as below
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() { }
}
使用子组件的父组件将为
The parent component that uses the child component will be as
@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'
}
}
LIVE DEMO
这篇关于角度2:组件交互,可选输入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文