我有一个实现,其中parent希望通过使用子组件上可用的@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'
  }
}

100

Angular相关问答推荐

RFDC.CommonJS或AMD依赖项可能会导致优化救助ANGURAL PROCEMENT with ngx-charts lib

在Angular 17中加载页面时打开打印对话框

使Angular 效果只执行一次

TransLoco合并本地和服务器端转换对象

如何确保[共享]组件是真正的哑组件?(Angular )

类是一个独立的组件,不能在Angular中的`@NgModule.bootstrap`数组中使用

当在server.ts文件中定义API路径时,Angular 17构建失败

如何处理后端删除元素后元素列表的刷新

在switchMap操作符中使用条件语句以进行第一次或随后的执行

Angular 迁移 14 到 15 / 16:angular universal 是否停止将 <!-- this page was prerendered with angular universal --> 用于预渲染页面?

PrimeNG:如何以编程方式更改分页器中的选定页面?

如何有条件地更新 Angular 路由解析器数据?

TypeError:this.restoreDialogRef.afterClosed 不是函数

console.log 返回 api 数据但 ERROR TypeError: Cannot read properties of undefined reading 'name'

Angular:将间隔与增量和减量相结合

使用 RxJS forkJoin 时传递参数的最佳方式

根据变量值更改按钮样式

在 Angular rxjs 中,我什么时候应该使用 `pipe` 与 `map`

将 [NgStyle] 与条件组合(if..else)

如何在 Angular CLI 6: angular.json 中添加 Sass 编译?