首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模具变更@Prop()检测

模具变更@Prop()检测
EN

Stack Overflow用户
提问于 2018-10-24 19:39:23
回答 1查看 4.2K关注 0票数 5

我怎样才能在模板中检测到道具的变化,在角度上是这样的:

但我不知道模板是怎么回事。

代码语言:javascript
复制
import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'my-name',
  template: `
      <h2>First name: {{name}} ({{_name}})</h2>
  `,
})
export class ChildComponent implements OnInit {
  private _name: string;
  constructor() {}

  get name(): string {
    // transform value for display
    return this._name.toUpperCase();
  }

  @Input()
  set name(name: string) {
    console.log('prev value: ', this._name);
    console.log('got name: ', name);
    this._name = name;
  }

  ngOnInit() {
    console.log('on init');
    console.log(this._name);
  }
}

我需要检测属性的变化

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-24 20:05:29

您可以在当属性更改时触发的方法上使用@Watch装饰符。

代码语言:javascript
复制
@Watch('name') 
onNameChanged(newValue: string, oldValue: string) {
  this._name = newValue;
}

@Watch**:**上的注释--这个装饰器只在道具上触发,这意味着在第一次设置道具时,不会调用onNameChanged()方法。为了拦截第一组,您必须使用componentWillLoad()钩子。 componentWillLoad(){ this.onNameChanged(this.name);}

工作示例:

代码语言:javascript
复制
import { Component, Prop, Watch } from '@stencil/core';

@Component({
  tag: 'my-name'
})
export class ChildComponent {

  private _name: string;

  @Prop() name: string = '';

  @Watch('name')
  onNameChanged(name: string) {
    console.log('prev value: ', this._name);
    console.log('got name: ', name);
    this._name = name.toUpperCase();
  }

  componentWillLoad(){
    this.onNameChanged(this.name);
  }

  render() {
    return (<h2>First name: {this.name} ({this._name})</h2>);
  }
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52976750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档