当通过 ngClass 指令添加类时,Angular 指令 css 类选择器不起作用。
这是我的代码示例,我还将在 link
添加游乐场@Directive({
selector: '.test',
standalone: true,
})
export class TestDirective {
constructor(public elementRef: ElementRef) {}
}
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, TestDirective],
styles: `
.prova {
padding:30px;
border: 5px solid black
}
.test {
padding:30px;
border: 5px solid red
}
`,
template: `
<button style="padding:5px; position:sticky; top:0" (click)="testScroll()"> test scroll</button>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div [ngClass]="{'test':true}">
test
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
<div class="prova">
ciao
</div>
Hello world!
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PlaygroundComponent implements OnInit {
test = viewChildren(TestDirective, { read: ElementRef });
ngOnInit(): void {
console.log(this.test());
}
testScroll() {
this.test()[0].nativeElement.scrollIntoView({ behavior: 'smooth' });
}
}
我已经尝试使用 @ViewChildren 并更改 onPush 检测策略,但没有任何效果。 我的目标是实现当动态添加特定类时滚动到元素的行为。
您的选择器的语法在这里是错误的:
您可以使用属性选择器来选择包含特定属性的 HTML 元素的目标。属性选择器包含在
[]
中
@Directive({
selector: '.test',
standalone: true,
})
此实现不会调用您的指令。
所以,你需要改变:
@Directive({
selector: '[test]',
standalone: true,
})
在模板中注入指令:
<div test [ngClass]="{'test':true}">
test
</div>