簡體   English   中英

角度2-將類別從一個組件更改為另一個組件

[英]Angular 2- change class from one component to another

我有2個組件-A,B並希望從A更改B的類。例如將ng-valid更改為ng-invalid

<A #a></A > <B> </B>

從BI希望將類賦予A,或將A的ng-valid類更改為ng-invalid。

看到這個笨拙的人以了解如何做到這一點: https ://plnkr.co/edit/wz771Lnnn3GjHWFmykGl?p=preview

正如您所評論的,您可以使用@Input來訪問該組件。

import {Component, NgModule, Input, ElementRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'AComp',
  template: 'a-component',
  styles: [
    ':host(.ng-valid) { color: green; font-weight: bold; }',
    ':host(.ng-invalid) { color: red; font-weight: bold; }'
    ]
})
export class AComp {

  constructor(private _eRef: ElementRef) {}

  public addClass(c: string) {
    console.dir(this._eRef);
    this._eRef.nativeElement.classList.add(c);
  }

  public removeClass(c: string) {
    this._eRef.nativeElement.classList.remove(c);
  }

}

@Component({
  selector: 'BComp',
  template: 'b-component'
})
export class BComp {

  @Input('a-comp') private _aComp: AComp;

  constructor() { }

  ngOnInit() {
    this._aComp.addClass('ng-valid')
    setTimeout(() => this._aComp.addClass('ng-invalid'), 1000);
    setTimeout(() => this._aComp.removeClass('ng-invalid'), 3000);
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <AComp #acmp></AComp>
      <br />
      <BComp [a-comp]="acmp"></BComp>
    </div>
  `,
})
export class App {
  constructor() {
    this.name = 'Angular2'
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, AComp, BComp ],
  bootstrap: [ App ]
})
export class AppModule {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM