简体   繁体   中英

Angular DOM elements are not showing

Hi I am using an UI Library (forced to, company issue..) which provides an Angular component, which renders a form.

Now I want to disable all of the input fields an buttons inside this form. But the component of the library doesn't provide me the possibility to pass a parameter to change the status to read only.

Now I have no other option to do dirty DOM hacking. However it doesn't seem to work.

Here is my HTML of my own component, where I render the Library Component:

<component-of-the-library #formComponent></component-of-the-library>

Now inside my own components class I reference it:

@ViewChild('formComponent', {read: ElementRef}) formComponent: ElementRef;

However when I use the nativeElement feature and the querySelectorAll() function I don't see the button elements:

ngAfterViewInit() {                
  console.log(this.formComponent.nativeElement);
 console.log(this.formComponent.nativeElement.querySelectorAll('button'))
}

The first line outputs the DOM of the library component. There I also see the buttons.

However the second line just returns an empty NodeList.

Am I missing something?

Instead of doing all these, come up with a div overlay and with the size of your form and make show or hide it based on your needs. It will be easier than disabling each form inputs and buttons. Also the overlay is not the component but your div.

我能够使用ViewChild()从父组件读取子组件中存在的DOM节点https://stackblitz.com/edit/angular-edmyur?file=src%2Fapp%2Fapp.component.ts

EDIT: I see another problem. AfterViewChecked gets called multiple times...

I found the answer myself. The problem is the LifeCycleHook. AfterViewInit works for your own component, but it doesn't wait for the child components to finish rendering.

When I use AfterViewChecked it works!

However I am still puzzled, that logging the nativeElement has always given me the correct DOM, even though it's still not rendered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM