【发布时间】:2019-03-21 11:06:20
【问题描述】:
我的问题涉及 *ngif 指令,一旦 *ngif=true 我希望 html 内容先呈现,然后我的“ModClass”指令可以执行它的工作。
我尝试实现 ngOnInit 和 ngViewInit 但没有运气,因为我相信 ngOnInit 在渲染 ngif 内容时触发,或者在生成父组件时可能更早。
对于 ngViewInit,我认为我需要订阅一些东西,但我不知道我需要订阅什么。 (我可能完全错了这会做更多的研究)
以下代码说明了我的问题以及 stacksblitz 链接,因此您不必在计算机上重新创建此代码来进行故障排除。
代码的作用是在按钮单击时切换与 ngIf 一起使用的布尔变量,如下所示:*ngIf='trigger'
ngIf 代码将显示一个带有默认 css 类“红色”的 div 块,但我的指令会将其更改为“蓝色”类。
更新
结果表明,只要我使用 ElementRef,ngViewInit 就可以正常工作。 感谢大家的帮助。
src/app/modify-class/modify-class.directive中的指令
import { Directive, OnInit } from '@angular/core'
@Directive({
selector: 'ModClass'
})
export class ModifyClassDirective implements OnInit {
constructor (private htmlElement: HTMLElement) {}
//should i try ngViewinit instead
ngOnInit () {
this.activateThisClass()
}
/*ngViewInit () {
this.activateThisClass()
}*/
//this function should execute once ng-if condition is true and html is rendered
activateThisClass () {
console.log('i\'ve been triggered')
const list = this.htmlElement.getElementsByClassName('red')
list.forEach(element => element.classList.remove('red'))
list.forEach(element => element.classList.add('blue'))
}
}
在 src/app/hello.component 中找到的 HTML/Hello 组件内容
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `
<h1>Hello {{name}}!</h1>
<button ModClass='' (click)="trigger=!trigger;"> click me </button>
<div *ngIf='trigger'>
<!-- This is what i want to change once it is rendered -->
<div ModClass='' class='red'> this will/should be overwritten and turn blue </div>
</div>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
@Input() trigger: boolean;
constructor() {this.trigger = false}
}
【问题讨论】:
标签: angular angular-directive lifecycle angular-ng-if