我正在使用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课程。 见截图:
你可以显示一些代码吗? –