Angular 4观察双向绑定属性更改

时间:2017-10-25 13:58:11

标签: angular typescript

我创建了一个toggle-sorting组件,用于检查当前排序参数是否匹配它的排序slug,并处理点击以输出更改

// toggle-sorting.component.ts

@Input() sortingSlug: string;
@Input() currSorting: string;
@Output() currSortingChange: EventEmitter<string> = new EventEmitter<string>();

@HostBinding('class.sorting-asc') activeAsc: boolean;
@HostBinding('class.sorting-desc') activeDesc: boolean;

/**
 * Watch sorting params changes and update binding
 */
ngOnChanges() {
    this.activeDesc = this.currSorting === this.sortingSlug;
    this.activeAsc = this.currSorting === '-' + this.sortingSlug;
}

/**
 * Watch click event to set sorting
 */
@HostListener('click') setSorting() {
    if (this.activeDesc) {
        this.currSortingChange.emit('-' + this.sortingSlug);
    } else {
        this.currSortingChange.emit(this.sortingSlug);
    }
}

我以这种方式使用它的父组件

// parent.component.html

// ... some layout
<th>
    <span toggle-sorting [(currSorting)]="sorting" sortingSlug="version">Scraper</span>
</th>
<th>
    <span toggle-sorting [(currSorting)]="sorting" sortingSlug="sites_count">Sites Scraped</span>
</th>
<th>
    <span toggle-sorting [(currSorting)]="sorting" sortingSlug="success_rate">Success rate</span>
</th>
// ... some layout

我的父组件中有全局sorting属性,它控制实际的排序参数,这是与toggle-sorting个孩子绑定的双向

// parent.component.ts

sorting: string = 'version';

我需要在每次全局排序参数更改时触发api调用,但我无法使用ngOnChanges进行观看,因为它不是@Input,我不想使用{{1}这里也是(性能方面),我不想在ngDoCheck中使用单独的@Input@Output(但是肯定它会适用于我的目的)。

在我的案例中,最好的选择是什么?

1 个答案:

答案 0 :(得分:3)

有几种方法可以做到这一点。

1。使用完整的ngModel格式:

  (ngModelChange)="onSortChanged($event)" [ngModel]="sorting"

  public onSortChanged(value:string):void
  {
     const changed = this._sorting !== value;
     this._sorting = value;
     if(changed) {
       //... do smth
     }
  }

2。使用get / set

private _sorting:string;

public get sorting():string
{
    return this._sorting;
}

public set sorting(value:string)
{
    const changed = this._sorting !== value;
    this._sorting = value;
    if(changed) {
       this.onSortingChanged();
    }
}