繁体   English   中英

Angular 2-从Component事件添加CSS类

[英]Angular 2 - Add CSS class from Component event

我将Angular 2与TypeScript和MDL一起使用,并且具有以下简单组件。 基本上,它是带有按钮的输入,然后是按钮下面的跨度的集合。 因此,您输入一些“标签”,然后单击按钮,并且集合将更新。

一个问题是当我像这样将项目添加到集合中时:

this.chips.push(this.chip);
this.chip = '';

然后,输入的值变为空白(根据需要),但是父div上的“ is-dirty” CSS MDL类未删除。 因此,我想做的就是从Component模板的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类。 看截图:

在此处输入图片说明

我需要在这里找到DIV元素并删除其“ is-dirty” CSS类

不要在element上这样做。 该类由ngModel设置,您应该使用ngModel的API将其.dirty状态设置为false。

更多

http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/

是的,is-dirty是由mdl设置的,而不是由ngModel设置的(如其他答案所建议)。 我不知道为什么几个月前尝试解决相反的问题时,这种情况没有出现:将模型更改注册到MDL输入元素 ,但绑定到类列表https://angular.io/docs/ ts / latest / guide / template-syntax.html#!#ngClass ,可能是更好的方法:

例如:

<div class="mdl-textfield mdl-js-textfield mdl-text-field--floating-label"
    [class.is-dirty]="false">

或对于mdl-tabs:

<div class="mdl-tabs__panel"
    [class.is-active]="someIsActiveBoolean">

或对于MDL复选框:

<label class="mdl-radio mdl-js-radio mdl-js-ripple-effect"
      [class.is-checked]="val == 1">

暂无
暂无

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

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