加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – Renderer multiple selectRootElement Issue

发布时间:2020-12-17 18:02:34 所属栏目:安全 来源:网络整理
导读:我正在尝试使用Renderer.selectRootElement从我的Component获取一些元素,如 here所述. 除非我只选择一个元素(plnkr),否则一切正常. 如您所见,我创建了一个组件: export class ExampleComponent implements OnInit{ @Input() start: any; @Input() end: any;
我正在尝试使用Renderer.selectRootElement从我的Component获取一些元素,如 here所述.

除非我只选择一个元素(plnkr),否则一切正常.

如您所见,我创建了一个组件:

export class ExampleComponent implements OnInit{
    @Input() start: any;
    @Input() end: any;

  constructor(public _renderer:Renderer){

  };

    ngOnChanges(){

    }
    ngOnInit(){
        console.log("NG ON CHAN START DATE",this.start);
        console.log("NG ON INIT END DATE",this.end);
        var container =  this._renderer.selectRootElement('.container');
        console.log(container);   
        var inner1 =  this._renderer.selectRootElement('.inner1');
        console.log(inner1);   
        var inner2 =  this._renderer.selectRootElement('.inner2');
        console.log(inner2);   
    }

}

当我尝试运行它时,我有一个错误:

EXCEPTION: The selector “.inner1” did not match any elements in [{{exampleData.end}} in MainViewComponent@3:65]

(但是,在我的应用程序中,当只找到第一个容器时,则找不到其他容器).

这有什么想法来自哪里?

UPDATE

我发现该指令未被完全调用 – 只有带有类容器的div被添加到HTML中.

enter image description here

解决方法

不要使用selectRootElement

其目的不是在组件视图中按选择器选择随机元素.

只需在DomRootRenderer中看到它的实现

selectRootElement(selector: string): Element {
    var el = DOM.querySelector(this._rootRenderer.document,selector);
    if (isBlank(el)) {
      throw new BaseException(`The selector "${selector}" did not match any elements`);
    }
    DOM.clearNodes(el);
    return el;
 }

你看到有趣的东西吗?它正在删除元素内的节点!为什么会这样做?因为它的目的是抓住根元素!那么哪一个是根元素?这听起来很熟悉吗?

<my-app>
    Loading...
</my-app>

是!那是根本要素.好的,但是如果我只想抓住元素,那么使用selectRootElement有什么问题?它返回没有子元素的元素,视图中没有任何变化!嗯,当然你仍然可以使用它,但是你将会像使用DynamicComponentLoader#loadAsRoot并手动订阅EventEmitter一样击败它的目的并滥用它.

好吧,毕竟它的名字,selectRootElement,几乎说它做什么,不是吗?

您有两种方法可以抓取视图中的元素,以及两个正确的选项.

>使用局部变量和@ViewChild

<div #myElement>...</div>

@ViewChild('myElement') element: ElementRef;

ngAfterViewInit() {
   // Do something with this.element
}

>创建一个指令来获取所需的元素

@Directive({
    selector : '.inner1,inner2' // Specify all children
    // or make one generic
    // selector : '.inner'
})
class Children {}

template : `
    <div class="container">
        <div class="inner1"></div>
        <div class="inner2"></div>

        <!-- or one generic
            <div class="inner"></div>
            <div class="inner"></div>
        -->
    </div>
`
class Parent (
    @ViewChildren(Children) children: QueryList<Children>;
    ngAfterViewInit() {
        // Do something with this.children
    }
)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读