角度2:组件交互,可选输入参数
发布时间:2020-12-17 08:02:56 所属栏目:安全 来源:网络整理
导读:我有一个实现,其中父级希望通过使用子组件中可用的@Input参数将某些数据传递给子组件.但是,此数据传输是可选的,父母可能会或可能不会根据要求传递它.是否可以在组件中包含可选的输入参数.我在下面描述了一个场景: parent child [showName]="true"/child //p
我有一个实现,其中父级希望通过使用子组件中可用的@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' } } LIVE DEMO (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |