Angular 2-将类从一个组件更改为另一个组件

时间:2016-09-20 04:40:53

标签: angular

我有2个组件 - A,B 并希望从A更改B的类。例如,将ng-valid更改为ng-invalid

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

从B我想把课程给A,或者将A的ng-valid课程改为ng-invalid。

1 个答案:

答案 0 :(得分:1)

请参阅此plunker以了解如何执行此操作: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 {}