简体   繁体   English

如何在Angular 2中使用指令获取新旧值?

[英]How can I get the old and new value using directive in Angular 2?

Does anyone know how can I get the old and new value inside the directive? 有谁知道如何在指令中获取旧值和新值? I need to compare if the value was changed to add a css class. 我需要比较是否更改了值以添加css类。

HTML: HTML:

<ul>
    <li *ngFor="let item of list" [addClass]="item.name">{{item.name}}</li>
</ul>

add-class.directive.ts 附加class.directive.ts

import { Directive, Input, OnInit } from '@angular/core';

@Directive({
  selector: '[addClass]'
})

export class AddClassDirective implements OnInit {
  @Input('addClass') addClass: string;

  constructor() {
  }

  ngOnInit() {
    console.log(this.addClass);
  }

}

method 1: 方法1:

ngOnChanges(changes: SimpleChanges) {
  if (changes['addClass'] && !changes['addClass'].isFirstChange()) {
    const prev: string = changes['addClass'].previousValue;
    const cur: string = changes['addClass'].currentValue;

    // do something with prev and cur
  }
}

method 2: 方法2:

private _addClass: string;

@Input() set addClass(value: string) {
  const prev = this._addClass;
  this._addClass = value;
  const cur = value;

  if (typeof prev !== 'undefined') {
    // do something with prev and cur
  }
}

get addClass() {
  return this._addClass;
}

Note that both these methods will also be called when the directive is first initialized. 请注意,在首次初始化指令时,这两种方法也会被调用。 In those cases the previous value will be undefined (which you can test for in ngOnChanges using the isFirstChange() method). 在这些情况下,先前的值将是undefined (您可以使用isFirstChange()方法在ngOnChanges中进行测试)。

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

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