动态插入mat-checkbox [英] dynamically insert mat-checkbox

查看:155
本文介绍了动态插入mat-checkbox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将<mat-checkbox>元素动态插入到组件中. 我插入了两个<mat-checkbox>元素.一个是静态插入的(即直接插入到模板文件中).

I want to dynamically insert a <mat-checkbox> element into a component. and I inserted two <mat-checkbox> elements. one inserted statically (i.e into the template file directly).

和另一个动态插入,并包含一个<mat-checkbox>和另一个普通复选框<input type="checkbox" />

and the other one inserted dynamically, and contains a <mat-checkbox> and another normal checkbox <input type="checkbox" />

第一个(静态插入的)呈现没有问题.

the first one (the statically inserted one) rendered without any problem.

动态输入的普通输入也没有问题.

also the normal input inserted dynamically without any problem.

,但是动态插入的<mat-checkbox>未能按预期呈现.

but the <mat-checkbox> that dynamically inserted didn't render as expected.

component.html:

component.html:

<mat-checkbox> checkbox (static) </mat-checkbox>

<div [innerHTML] = "test2">

component.ts:

component.ts:

 this.test= ` 
     <mat-checkbox>mat-checkbox</mat-checkbox><br />
     <input type="checkbox" /> normal checkbox   
  `

  this.test2 = this.sanitizer.bypassSecurityTrustHtml(this.test);

我在stackblitz上创建了一个复制品:

I created a Reproduction on stackblitz:

https://stackblitz.com/edit/angular-hsjevo

我还需要根据类别创建复选框,并在每个子类别之前添加一些额外的空格

also I need to create checkboxes from categories, and append some extra spaces before each sub-category

即:

  • 类别
    • 子类别
      • 子类别的子项
      • category
        • sub category
          • sub of sub category

          每个类别或子类别为<mat-checkbox value="$id"> $title

          推荐答案

          innerHTML属性只能解析和呈现常规HTML元素(如输入等).要动态创建mat-checkbox之类的Angular组件,您需要通知Angular关于那些组件.让我们看看如何做到这一点:

          innerHTML property of div tag can only parse and render regular HTML elements like input, etc. To dynamically create Angular components like mat-checkbox, you need to inform Angular about those components. Let's see how this can be done below:

          我们在AppComponent模板中需要一个占位符,可以在其中动态添加mat-checkbox组件.在这种情况下,我们可以使用<ng-template>标记作为占位符.

          We need a placeholder in the AppComponent template where we can add the mat-checkbox component dynamically. We can use <ng-template> tag as a placeholder in this case.

          app.component.html

          <mat-checkbox>mat-checkbox (static)</mat-checkbox> <hr />
          
          
          dynamic angular component:<br/>
          <ng-template #placeholder></ng-template>
          

          在AppComponent打字稿文件中,我们需要引用此占位符并附加mat-checkbox组件.找到内嵌注释以进行解释.

          In AppComponent typescript file, we need to refer this placeholder and append the mat-checkbox component. Find the inline comments for explanation.

          app.component.ts

          import {
            Component,
            ComponentFactoryResolver,
            OnInit,
            Renderer2,
            ViewChild,
            ViewContainerRef
          } from '@angular/core';
          import {MatCheckbox} from '@angular/material';
          
          @Component({
            selector: "my-app",
            templateUrl: "./app.component.html",
            styleUrls: ["./app.component.css"]
          })
          export class AppComponent implements OnInit {
            // Get reference to the ng-template placeholder tag
            @ViewChild('placeholder', {read: ViewContainerRef, static: true}) placeholder: ViewContainerRef;
          
            constructor(
              private resolver: ComponentFactoryResolver,
              private renderer: Renderer2) {}
          
            ngOnInit() {
              this.createComponent();
            }
          
            createComponent() {
              // creating the mat-checkbox tag body content
              let content = this.renderer.createText(' mat-checkbox (dynamic)');
              // clear any previously appended element or component
              this.placeholder.clear();
              // resolve the MatCheckbox component and get the factory class to create the component dynamically
              let factory = this.resolver.resolveComponentFactory(MatCheckbox);
              // create the component and append to the placeholder in the template
              let ref = this.placeholder.createComponent(factory);
              // set the mat-checkbox body content
              (ref.location.nativeElement as HTMLElement).appendChild(content);
            }
          }
          

          为使上述代码正常工作,我们需要通知Angular我们希望在运行时解析MatCheckbox组件.在app.module.ts中进行以下更改.

          In order for the above code to work, we need to inform Angular that we would be expecting to resolve the MatCheckbox component at runtime. Make the following changes in app.module.ts.

          app.module.ts

          import { NgModule } from '@angular/core';
          import { BrowserModule } from '@angular/platform-browser';
          import { FormsModule } from '@angular/forms';
          import { MatCheckboxModule, MatCheckbox } from '@angular/material';
          
          import { AppComponent } from './app.component';
          import { HelloComponent } from './hello.component';
          
          
          @NgModule({
            imports:      [ BrowserModule, FormsModule, MatCheckboxModule ],
            declarations: [ AppComponent, HelloComponent ],
            // Inform Angular about those components which will be created dynamically by including them in entryComponents field
            entryComponents: [ MatCheckbox ],
            bootstrap:    [ AppComponent ]
          })
          export class AppModule { }
          

          现在,您应该能够看到在运行时动态创建的mat-checkbox. 在此处查看完整的示例( https://stackblitz.com/edit/angular-e7vhue )

          Now you should be able to see the mat-checkbox created dynamically at runtime. View the complete example here (https://stackblitz.com/edit/angular-e7vhue)

          有关更多信息,请参阅此文章.

          For more information, refer this article.

          希望这对您的查询有所帮助.

          Hope this helped your query.

          这篇关于动态插入mat-checkbox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆