简体   繁体   English

Angular 6 Renderer2 / 3-如何向元素添加类?

[英]Angular 6 Renderer2/3 - how to add class to element?

//Parent Component html:
<div class="modal" id="modal" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
               <router-outlet>
               </router-outlet>
             </div>
       </div>
   </div>
</div>

I want to apply class "modal-lg" to div with class modal-dialog when my "UPIComponent" named child component is loaded. 当加载名为子组件的“ UPIComponent”时,我想将类“ modal-lg”应用于div和modal-dialog类。 How can i achieve the same? 我怎样才能达到同样的目的?

You need to use ngClass to achieve this. 您需要使用ngClass来实现。 You can pass a condition to it: 您可以为其传递条件:

<some-element [ngClass]="{'modal-lg': yourCondition}">...</some-element> . <some-element [ngClass]="{'modal-lg': yourCondition}">...</some-element>

In relation to obtaining this condition, (which in your case is when your child component is loaded), you will have to pass this information from the child component to the parent (telling the parent that it's loaded). 关于获得此条件(在您的情况下,这是在加载子组件时),您将必须将此信息从子组件传递给父组件(告诉父组件已加载)。

The ngAfterViewInit and the @Output() decorator will do the trick. ngAfterViewInit@Output()装饰器将完成此任务。

Just pass a value ( isLoaded a boolean type, for example) to the parent then the parent will use ngClass : [ngClass]="{'modal-lg': isChildLoaded} ". 只需将一个值(例如isLoaded为布尔类型)传递给父级,然后父级将使用ngClass[ngClass]="{'modal-lg': isChildLoaded} ”。

Use Router Template variable and activate event to pass the template ref to get the component name then use ngClass to add desired class 使用路由器模板变量并激活事件以传递模板引用以获取组件名称,然后使用ngClass添加所需的类

<div class="modal" id="modal" data-backdrop="static" data-keyboard="false">
    <div [ngClass]="modelClass==='UPIComponent' ? 'model-lg': 'model-dialog'" >
        <div class="modal-content">
            <div class="modal-body">
                <router-outlet #o="outlet"
                 (activate)='onActivate(o)'>
                 </router-outlet>
             </div>
       </div>
   </div>
</div>

component.ts component.ts

 modelClass = '';
  onActivate(o) {
    this.modelClass = o.activatedRoute.component.name;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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