我的问题涉及到* ngif指令,当一次* ngif = true时,我希望先显示html内容,然后再执行'ModClass'指令。
我尝试实现ngOnInit和ngViewInit,但是没有运气,因为我相信ngOnInit在呈现ngif内容时或在生成父组件时更早触发。
另外,对于ngViewInit,我认为我需要订阅某些内容,但我不知道我需要订阅什么。(对此我可能完全错了,它将进行更多研究)
以下代码说明了我的问题以及具有stacksblitz链接的情况,因此您无需在计算机上重新创建此代码即可进行故障排除。
代码要做的是单击按钮,它切换了一个与ngIf一起使用的布尔变量:* ngIf ='trigger'
ngIf代码将显示带有默认CSS类'red'的div块,但是我的指令会将其更改为'blue'类。
更新
事实证明,只要我使用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}
}
链接到Stackblitz链接
我不知道您是否打算按照问题中所述使用指令(因为red
该类似乎仅在元素不存在时才应用),但是您可以更改以下两点以使其起作用:
ModClass
为[ModClass]
ElementRef
指令构造函数而不是HTMLElement
这是修改后的代码:
import { Directive, ElementRef, OnInit } from '@angular/core'
@Directive({
selector: '[ModClass]'
})
export class ModifyClassDirective implements OnInit {
constructor (private elementRef: ElementRef) {}
ngOnInit () {
this.activateThisClass()
}
activateThisClass () {
console.log("activateThisClass triggered!")
const element = this.elementRef.nativeElement;
element.classList.remove('red');
element.classList.add('blue');
}
}
请参阅修改后的stackblitz。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句