如何设置Angular 2组件属性的默认值? [英] How to set default values for Angular 2 component properties?

查看:341
本文介绍了如何设置Angular 2组件属性的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写Angular 2.0组件时,如何设置属性的默认值?

When writing Angular 2.0 components, how does one set default values for properties?

例如-我想默认将foo设置为'bar',但是绑定可能会立即解析为'baz'.如何在生命周期挂钩中发挥作用?

For example - I want to set foo to 'bar' by default, but the binding might immediately resolve to '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>

登录到控制台:

'baz'
'bar'
'baz'

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

登录到控制台:

'bar'
undefined
undefined

推荐答案

这是一个有趣的话题. 您可以使用两个生命周期挂钩来弄清楚它是如何工作的:ngOnChangesngOnInit.

That is interesting subject. You can play around with two lifecycle hooks to figure out how it works: ngOnChanges and ngOnInit.

基本上,当您将默认值设置为Input时,这意味着仅在该组件上没有值的情况下才使用该值. 并且有趣的部分将在组件初始化之前进行更改.

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. And the interesting part it will be changed before component will be initialized.

假设我们有这样的组件,它们带有两个生命周期钩子和一个来自input的属性.

Let's say we have such components with two lifecycle hooks and one property coming from 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);
  }

}

情况1

HTML中包含的组件,但未定义property

因此,我们将在控制台中看到: Init default

As result we will see in console: Init default

这意味着未触发onChange.初始化被触发,并且property的值为预期的default.

That's mean onChange was not triggered. Init was triggered and property value is default as expected.

情况2

包含在html中且具有设置属性的组件 <cmp [property]="'new value'"></cmp>

结果,我们将在控制台中看到:

As result we will see in console:

Changed new value Object {}

Init new value

这很有趣.首先触发onChange钩子,将property设置为new value,并且先前的值是空对象!并且只有在此之后,才使用新值property触发onInit挂钩.

And this one is interesting. Firstly was triggered onChange hook, which setted property to new value, and previous value was empty object! And only after that onInit hook was triggered with new value of property.

这篇关于如何设置Angular 2组件属性的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆