我正在尝试使用ViewChild获取子组件的元素,但无法找到实现此目的的方法.
我们在模板中说:
...
<some-comp #someComp></some-comp>
...
Run Code Online (Sandbox Code Playgroud)
并获得此参考:
import { SomeComponent } from './some-comp/some-comp.component';
...
@ViewChild('someComp') someComp: SomeComponent;
...
ngOnInit() {
// this.someComp.nativeElement? <-- how to get nativeElement?
}
Run Code Online (Sandbox Code Playgroud)
我试图这样做的原因是通过使用scrollToHTMLElement的函数自动滚动到该子组件的位置来将视图集中到该子组件.(请参阅如何在单击时将元素滚动到视图中)
我可以通过给那个子组件提供id并使用document.getElementById()来检索它,但我想知道是否有办法使用模板引用变量或任何角度方式来执行此操作.
提前致谢!
我正在尝试测试应用于组件的宿主元素的样式,但看起来fixture.debugElement.nativeElement.style如果通过:host样式表中的选择器应用应用的样式,则它们不会显示。
假设我们有按钮组件:
@Component({
selector: 'test-button',
templateUrl: './button.component.html',
styleUrls: ['./button.component.scss'],
})
export class ButtonComponent implements OnInit {
constructor() {}
ngOnInit() {}
}
Run Code Online (Sandbox Code Playgroud)
并且button.component.scss包含:
:host {
border-radius: 4px;
}
Run Code Online (Sandbox Code Playgroud)
在我们的规范文件中:
describe('ButtonComponent', () => {
let fixture: ComponentFixture<TestApp>;
let buttonDebugElement: DebugElement;
let testComponent: TestApp;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ButtonModule],
declarations: [TestApp],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestApp);
testComponent = fixture.componentInstance;
buttonDebugElement = fixture.debugElement.query(By.css('test-button'));
});
describe('styles', () => {
let hostElement: HTMLElement;
beforeEach(() => {
hostElement = …Run Code Online (Sandbox Code Playgroud) 在角度2中创建动态组件时,我发现此过程需要ViewContainerRef才能将新创建的组件添加到DOM.
Angular 2动态选项卡,用户单击所选组件 https://www.lucidchart.com/techblog/2016/07/19/building-angular-2-components-on-the-fly-a-dialog-box-example/
在将输入和输出传递给那些动态创建的组件时,我在上面的第二个链接中找到了答案:https: //codedump.io/share/kQakwDKNu0iG/1/passing-input-while-creating-angular-2-组件的动态使用-componentresolver
但是,如果我要创建一个名为shape.service的服务,其中包含使用bgColor等输入返回不同形状组件的函数,我不知道该服务如何在不指定DOM位置的情况下创建组件,以及容器组件如何接收这个返回的组件(可能是它的类型将是ComponentRef)来自服务并将其注入DOM容器组件指定.
例如,服务包含一个功能:
getCircle(bgColor:string): ComponentRef<Circle> {
let circleFactory = componentFactoryResolver.resolveComponentFactory(CircleComponent);
let circleCompRef = this.viewContainerRef.createComponent(circleFactory);
circleCompRef.instance.bgColor = bgColor;
return circleCompRef;
}
Run Code Online (Sandbox Code Playgroud)
第一个问题在这里提出,我如何ViewContainerRef在此期间指出无处?我导入viewContainerRef的原因是动态创建组件.
第二个问题是容器组件@Input从服务接收特定于输入的内容后,它将如何注入其DOM?
提前致谢!
更新: 我认为上面的问题不够具体.我遇到的情况是:
这意味着服务调用组件不知道这些componentRef将被注入的位置.简而言之,我需要可以随时随地注入的独立组件对象.
我已经好几次读过rumTimeCompiler解决方案,但我真的不知道它是如何工作的.与使用viewContainerRef创建组件相比,似乎有太多工作要做.如果我找不到其他解决方案,我会深入研究一下......