angular - 模板更改@Prop() 检测

标签 angular stenciljs

我如何检测模板中的 Prop 变化, Angular 是这样的:

但我不知道如何在模板中。

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);
  }
}

我需要检测属性变化

最佳答案

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

@Watch('name') 
onNameChanged(newValue: string, oldValue: string) {
  this._name = newValue;
}

Note on @Watch: this decorator only trigger on prop changed, it means the onNameChanged() method won't be called the first time that prop is set. In order to intercept the first set, you have to use the componentWillLoad() hook.

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


工作示例:
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>);
  }
}

关于angular - 模板更改@Prop() 检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52976750/

相关文章:

css - 更改所选选项卡的颜色,属于 TabMenu PRIMENG - 样式

javascript - Angular 2 如何使用驼峰命名法处理属性

reactjs - 从 StencilJS 组件内部渲染 React 组件并将插槽映射到 props.children

visual-studio-code - VSCode 调试器在 Jest 测试中不起作用

javascript - 模板项目中现有的模板组件

javascript - Angular 中的异步编程

angular - 将 Angular 应用程序升级到 Bootstrap 4.0.0

jquery - 错误 $ 未在 Angular Universal 中定义

css - 模具 |在组件中使用 CSS "+ Selector "

javascript - npm init 模板如何工作?