首页 文章

有条件地在角度2中切换类

提问于
浏览
7

每当点击“app-header”组件中的按钮时,我需要在app-component中切换“活动”类 . 这是我的app-component.html,

<div class="off-canvas">
    <app-header><app-header>
    <app-home></app-home>
    <app-footer></app-footer>
</div>

APP-了header.html

<div>
<!--Some code-->
<button></button>
</div>

我怎么能只用角度来做这个,因为div和按钮是2个不同的组件????请帮助我是棱角分明的新手!!!

3 回答

  • 6

    你可以使用EventEmitter .

    APP-了header.html

    <div>
    <!--Some code-->
    <button (click)="emitClick()"></button>
    </div>
    

    APP-header.ts

    @Output() _clickEvent:EventEmitter<any>=new EventEmitter();
    
    constructor(){
    }
    ngOnInit(){
    }
    emitClick($event){
      this.clickEvent.emit()
    }
    

    APP-component.html

    <div class="off-canvas" [ngClass]="{'someClassName':active}">
        <app-header (_clickEvent)="toggleActive($event)"><app-header>
        <app-home></app-home>
        <app-footer></app-footer>
    </div>
    

    APP-component.ts

    active:boolean=false;    
        constructor(){
        }
        ngOnInit(){
        }
       toggleActive($event){
        // Insert click event handling here
       }
    

    您应该在app-component.ts中声明活动变量并将其初始化为Boolean . 每次单击都会导致活动在true和false之间切换 . 只要'active'变量为true,ngClass就会添加一个名为'someClassName'的类 .

  • 4

    您可以将对象绑定到[ngClass]指令:

    <div [ngClass]="{'active': isActive, 'disabled': isDisabled}">
    

    要在组件之间共享数据,请参阅以下答案:https://stackoverflow.com/a/45371025/1791913

  • 2

    您可以创建公共服务并将变量存储为public,例如:

    @Injectable()
    export class DataService{
        foo:string;
    }
    

    然后在两个组件中使用变量作为共享变量,例如:

    @Component({...})
    export class FooComponent{
        constructor(private dataService:DataService){}
    
        foo():void{
            console.log(this.dataService.foo);
        }
    }
    

相关问题