我有一个测试部分,其中列有两项指示(一项是属性指令)。 在测试部分,Im利用儿童观察所尝试和参考<代码>ngAfterViewInit的手稿。 但是,每一份指令Im检测结果的 编号:<0>未界定>。 当我检查该页时,这些指示出现在OMD。
Here is a StackBlitz example: https://stackblitz.com/edit/stackblitz-starters-f3g4sv?file=src%2Ftest.component.ts
测试部分:
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
QueryList,
ViewChild,
ViewChildren,
ViewEncapsulation,
} from @angular/core ;
import { CommonModule } from @angular/common ;
import { TestContainerDirective } from ./test-container.directive ;
import { OtherContainerDirective } from ./other-test-container.directive ;
@Component({
selector: app-test ,
standalone: true,
imports: [CommonModule, OtherContainerDirective],
templateUrl: ./test.component.html ,
styleUrl: ./test.component.scss ,
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppTestComponent implements AfterViewInit {
@ViewChild(TestContainerDirective)
public _testContainerRef!: TestContainerDirective;
@ViewChild(OtherContainerDirective)
public _otherContainerRef!: OtherContainerDirective;
@ViewChildren(TestContainerDirective)
_testContainerChildren!: QueryList<TestContainerDirective>;
constructor() {}
public ngAfterViewInit(): void {
console.log( _testContainerRef , this._testContainerRef);
console.log( _otherContainerRef , this._testContainerRef);
console.log( _testContainerChildren , this._testContainerChildren);
setTimeout(() => {
console.log( _testContainerRef , this._testContainerRef);
console.log( _otherContainerRef , this._testContainerRef);
}, 0);
}
}
其模板如下:
<p>This is the test component</p>
<span>
Open the console and look for the references to the directives below
</span>
<p></p>
<div appTestContainer>test container</div>
<other-container>other container</other-container>
而且 测试指示如下:
@Directive({
standalone: true,
selector: [appTestContainer] ,
})
export class TestContainerDirective {
constructor(public viewContainer: ViewContainerRef) {}
}
@Directive({
standalone: true,
selector: other-container ,
})
export class OtherContainerDirective {
constructor(public viewContainer: ViewContainerRef) {}
}
这似乎与在笔试中的做法一样,因此我不敢肯定我所缺的东西。 任何帮助都值得赞赏。