2016-10-09 37 views
4

componentA.ts動態更新[選中]在Angular2

@Input() array; 

<input type="checkbox" [checked]="array | contains: value"/> 
<label>{{array.length}}</label> 

componentB.ts

@Component({ 
    selector: 'app-component-b', 
    templateUrl: './app.component-b.html' 
}) 
export class AppComponentB { 
    array = [1, 2, 3]; 
} 

我更新在一些其他組件array。雖然label正確更新數組的長度,但複選框似乎未被更新。 contains只是一個簡單的管道,用於檢查value是否爲array的一部分。我在contains管道中放置了一個console.log,並且只在頁面呈現時纔得到輸出,而不是在array更改時獲得輸出。爲什麼是這樣?

謝謝..

+0

你能告訴哪兒數組定義?它在服務還是組件? – micronyks

+0

這只是組件中的一個變量。我在上面添加了一些代碼。 – 7ball

回答

3

這是因爲如果你用push新項目添加到數組,那麼數組引用沒有改變,而純粹的管道將只當它檢測到純變化的輸入值執行(arrayvalue你的情況)

有兩種解決方法:

1)返回新數組

this.array = this.array.concat(4) 

this.array = [...this.array, 4]; 

Plunker

2)使用不純的管

@Pipe({name: 'contains', pure: false}) 
export class ContainsPipe implements PipeTransform { 

Plunker

詳情參見

+0

謝謝!就是這樣。 – 7ball