我正在使用Angular 2與TypeScript和MDL,並具有以下簡單的組件。基本上它是一個按鈕的輸入,然後是它下面的一個跨度集合。所以你輸入一些「標籤」,然後點擊按鈕,集合被更新。Angular 2 - 從組件事件添加CSS類
的一個問題是,當我添加項目集合是這樣的:
this.chips.push(this.chip);
this.chip = '';
則輸入的值將變爲空白(通緝),但在父DIV的「是髒」 CSS MDL類沒有刪除。所以我想要做的只是從組件模板中的DIV元素中刪除類。
如何在Angular2中查詢DOM並操作它(添加/刪除CSS類)? 我正在試玩Renderer,但目前還沒有運氣。
注意:我無法綁定這個「is-dirty」類,因爲MDL javascript手動更新它,當輸入文本時。
代碼:
import {Component, View, Directive, Input, ElementRef, Renderer} from 'angular2/core'
import {NgIf, NgFor} from 'angular2/common'
@Component({
selector: 'chipCollection'
})
@View({
directives: [NgIf, NgFor],
template: `
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="chip" [(ngModel)]="chip" (keyup.enter)="addChip()">
<label class="mdl-textfield__label" for="chip">{{ label }}</label>
<label class="mdl-button mdl-js-button mdl-button--icon aa-mdl-input-button">
<i class="material-icons" (click)="addChip()">add</i>
</label>
</div>
<div *ngIf="chips.length > 0">
<span *ngFor="#chip of chips" class="aa-chip">{{ chip }}</span>
</div>
`
})
export class ChipCollection {
@Input() chips: Array<string> = ["chip1", "chip2"];
@Input() label: string;
chip: string;
private renderer: Renderer;
private element: ElementRef;
constructor(renderer: Renderer, element: ElementRef){
this.renderer = renderer;
this.element = element;
}
addChip() {
if(this.chip) {
this.chips.push(this.chip);
this.chip = '';
debugger; //testing here...
// what I need to do here is to find the DIV element and remove its "is-dirty" CSS class, any ideas?
this.renderer.setElementClass(this.element.nativeElement, 'is-dirty', false);
}
}
}
編輯: 這裏有兩個 「骯髒」 類。我猜ng-dirty是由ngModel添加的。不過,我還需要刪除父母的「骯髒」。我認爲這是MDL課程。 見截圖:
你可以顯示一些代碼嗎? –