简体   繁体   English

如何为 Angular 2 组件属性设置默认值?

[英]How to set default values for Angular 2 component properties?

When writing Angular 2.0 components, how does one set default values for properties?在编写 Angular 2.0 组件时,如何设置属性的默认值?

For example - I want to set foo to 'bar' by default, but the binding might immediately resolve to 'baz' .例如 - 我想默认将foo设置为'bar' ,但绑定可能会立即解析为'baz' How does this play out in the lifecycle hooks?这如何在生命周期钩子中发挥作用?

@Component({  
    selector: 'foo-component'
})
export class FooComponent {
    @Input()
    foo: string = 'bar';

    @Input()
    zalgo: string;

    ngOnChanges(changes){
          console.log(this.foo);
          console.log(changes.foo ? changes.foo.previousValue : undefined);
          console.log(changes.foo ? changes.foo.currentValue : undefined);
    }
}

Given the following templates, this is what I expect the values would be.鉴于以下模板,这就是我期望的值。 Am I wrong?我错了吗?

<foo-component [foo] = 'baz'></foo-component>

Logged to console:登录到控制台:

'baz'
'bar'
'baz'
<foo-component [zalgo] = 'released'></foo-component>

Logged to console:登录到控制台:

'bar'
undefined
undefined

That is interesting subject.这是个有趣的话题。 You can play around with two lifecycle hooks to figure out how it works: ngOnChanges and ngOnInit .您可以使用两个生命周期钩子来弄清楚它是如何工作的: ngOnChangesngOnInit

Basically when you set default value to Input that's mean it will be used only in case there will be no value coming on that component.基本上,当您将默认值设置为Input ,这意味着只有在该组件上没有值的情况下才会使用它。 And the interesting part it will be changed before component will be initialized.有趣的部分将在组件初始化之前进行更改。

Let's say we have such components with two lifecycle hooks and one property coming from input .假设我们有这样的组件,它有两个生命周期钩子和一个来自input属性。

@Component({
  selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
  @Input() property: string = 'default';

  ngOnChanges(changes) {
    console.log('Changed', changes.property.currentValue, changes.property.previousValue);
  }

  ngOnInit() {
    console.log('Init', this.property);
  }

}

Situation 1情况一

Component included in html without defined property value包含在 html 中的组件没有定义的property

As result we will see in console: Init default结果我们将在控制台中看到: Init default

That's mean onChange was not triggered.这意味着没有触发onChange Init was triggered and property value is default as expected. Init 被触发, property值是预期的default值。

Situation 2情况二

Component included in html with setted property <cmp [property]="'new value'"></cmp>包含在 html 中并具有设置属性<cmp [property]="'new value'"></cmp>

As result we will see in console:结果我们将在控制台中看到:

Changed new value Object {} Changed new value Object {}

Init new value Init new value

And this one is interesting.而这个很有趣。 Firstly was triggered onChange hook, which setted property to new value , and previous value was empty object !首先触发onChange钩子,将property设置为new value ,之前的值为空对象 And only after that onInit hook was triggered with new value of property .并且只有在onInit钩子被触发后property新值。

Here is the best solution for this.这是最好的解决方案。 (ANGULAR All Version) (角度所有版本)

Addressing solution : To set a default value for @Input variable .解决方案为@Input 变量设置默认值 If no value passed to that input variable then It will take the default value .如果没有值传递给该输入变量,则它将采用默认值

I have provided solution for this kind of similar question.我已经为这种类似的问题提供了解决方案。 You can find the full solution from here您可以从这里找到完整的解决方案

export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM