gpt4 book ai didi

javascript - Angular 2 以编程方式绑定(bind) ngIf

转载 作者:行者123 更新时间:2023-11-29 21:11:23 25 4
gpt4 key购买 nike

我正在构建一个具有两种状态的页眉组件:

  • 标准:显示详细内容
  • 紧凑:显示最少的内容

这个想法是这个组件可以像这样添加到任何“页面”组件:

home.component.html

<app-page-header>

<app-page-header-standard>
// Standard Content
</app-page-header-standard>

<app-page-header-compact>
// Compact Content
</app-page-header-compact>

</app-page-header>

我目前的代码:

page-header.component.html

<div class="wrapper">

<!-- The standard and compact components are transcluded here -->
<ng-content></ng-content>

<a (click)="toggleHeaderState()">Toggle me</a>
</div>

page-header.component.ts

import {Component, OnInit, ViewEncapsulation, Input, ContentChild} from '@angular/core';
import {PageHeaderStandardComponent} from "./page-header-standard.component";
import {PageHeaderCompactComponent} from "./page-header-compact.component";

@Component({
selector: 'app-page-header',
templateUrl: './page-header.component.html',
styleUrls: ['./page-header.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class PageHeaderComponent implements OnInit {

@ContentChild(PageHeaderStandardComponent) headerStandard: PageHeaderStandardComponent;
@ContentChild(PageHeaderCompactComponent) headerCompact: PageHeaderCompactComponent;

/**
* Toggle the header standard and compact state
* @type {boolean}
*/
@Input() compacted: boolean = false;

constructor() {
}

ngOnInit() {
console.log(this.headerStandard);
console.log(this.headerCompact);

// TODO
// Bind compact and standard component to compacted input
// i.e. one hides while the other shows
}

toggleHeaderState() {
this.compacted = !this.compacted;
}
}

问题:如何将 ngIf 分配给 ngOnInit 函数中的两个 ContentChild 组件?即当 compacted 输入为 true 时显示一个组件,然后当 compacted 输入为 false 时显示另一个组件

最佳答案

您不能动态添加 ngIf。您可以设置隐藏属性

@ContentChild(PageHeaderStandardComponent, {read: ElementRef}) headerStandard: PageHeaderStandardComponent;
@ContentChild(PageHeaderCompactComponent, {read: ElementRef}) headerCompact: PageHeaderCompactComponent;

ngAfterViewInit() {
console.log(this.headerStandard);
console.log(this.headerCompact);
this.headerStandard.nativeElement.setAttribute('hidden', !compacted);
this.headerCompact.nativeElement.setAttribute('hidden', compacted);
}

关于javascript - Angular 2 以编程方式绑定(bind) ngIf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41712313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com