【问题标题】:How to set default parameter for @Input in Angular2?如何在Angular2中为@Input设置默认参数?
【发布时间】:2016-06-20 17:32:00
【问题描述】:

假设我有一个组件会显示name 属性,所以大致是这样的:

import {Component, Input} from 'angular2/core';

@Component({
  selector: 'demo',
  template: `<div>{{name}}</div>`,
  styles: [``],
})
export class Demo {
  @Input() name: string;
}

问题是,当有人使用这个组件但没有传递任何name 属性时,我怎么能显示[noname]

想到的唯一解决方案是在模板中使用逻辑运算符,例如{{ name || '[noname]' }}

【问题讨论】:

    标签: javascript typescript angular


    【解决方案1】:

    试试

    @Input() name: string = 'noname';
    

    【讨论】:

    • 这对我不起作用。即使我将其设置为模板中的另一个值,它也使用默认值。
    【解决方案2】:

    我认为您可以使用模板的想法。所以应该是:

    在组件中:

    @Input () name:String;
    

    在模板中:

    <div>{{ name != '' ? name : '[no name]' }}</div>
    

    这将检查名称是否为空,如果名称通过,则使用“[无名称]”或插入名称。

    【讨论】:

      【解决方案3】:

      在组件中你应该像这样初始化:

      @Input () name:String='';
      

      在 HTML 中你可以使用:

      {{ name ===''?  'empty string': name }}
      

      【讨论】:

        【解决方案4】:

        您可以使用 setter 拦截 @Input() 并让其由私有字段支持。在 setter 中,您执行 nullcheck,因此字段仅设置为非 null 值。最后,您将模板绑定到已设置初始值的私有字段。

        【讨论】:

          【解决方案5】:

          使用 angular 8 和默认 tslint 设置您的 IDE 会注意到:

          所以直接写就好了:

          @Input() addclass = '';
          

          没有任何“类型注释”。

          【讨论】:

          • 删除类型注释使其工作。但为什么?不应该无所谓吗?
          • 没关系。这是一个 linting 建议,仅用于标准化您的代码并使其更具可读性。如果您希望保留类型注释,可以禁用 tslint 中的规则。
          【解决方案6】:

          这是解决此问题的正确方法。 (角度 2 到 9)

          解决方案:为@Input 变量设置一个默认值。如果没有值传递给该输入变量,那么它将采用默认值。

          例子:

          我有一个名为 Bike 的对象接口:

          export interface bike {
            isBike?: boolean;
            wheels?: number;
            engine?: string;
            engineType?: string;
          }
          

          您创建了一个名为 app-bike 的组件,您需要在其中使用 angular 的 @input 装饰器传递自行车的属性。但是你希望 isBike 和 Wheels 属性必须有一个默认值(即.. isBike: true, Wheels: 2)

          export class BikeComponent implements OnInit {
            private _defaultBike: bike = {
              // default isBike is true
              isBike: true,
              // default wheels  will be 2
              wheels: 2
            };
          
            @Input() newBike: bike = {};
          
            constructor() {}
          
            ngOnInit(): void {
          
             // this will concate both the objects and the object declared later (ie.. ...this.newBike )
             // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT
          
              this.newBike = { ...this._defaultBike, ...this.newBike };
             //  console.log(this.newBike);
            }
          }
          

          更详细的文章请参考this

          参考here的解构赋值

          【讨论】:

            猜你喜欢
            • 2019-02-06
            • 1970-01-01
            • 1970-01-01
            • 2013-03-25
            • 2019-07-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-04-30
            相关资源
            最近更新 更多