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

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

问题描述

我想将 元素动态插入到组件中.我插入了两个 元素.一个静态插入(即直接插入模板文件).

另一个是动态插入的,包含一个和另一个普通的checkbox

第一个(静态插入的)渲染没有任何问题.

也是动态插入的正常输入没有任何问题.

但是动态插入的 没有按预期呈现.

component.html:

复选框(静态)</mat-checkbox><div [innerHTML] = "test2">

component.ts:

 this.test= `<mat-checkbox>mat-checkbox</mat-checkbox><br/><input type="checkbox"/>普通复选框`this.test2 = this.sanitizer.bypassSecurityTrustHtml(this.test);

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

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

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

即:

  • 类别
    • 子类别
      • 子类别的子
  • 类别2

每个类别或子类别是 $title

解决方案

div 标签的innerHTML属性只能解析和渲染常规的HTML元素,如input等.要动态创建像mat-checkbox这样的Angular组件,需要通知Angular关于那些组件.下面让我们看看如何做到这一点:

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

app.component.html

mat-checkbox(静态)<小时/>动态角度分量:<br/><ng-template #placeholder></ng-template>

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

app.component.ts

import {成分,ComponentFactoryResolver,初始化,渲染器2,视图子,视图容器引用来自'@angular/core';从@angular/material"导入{MatCheckbox};@成分({选择器:我的应用程序",templateUrl: "./app.component.html",styleUrls: ["./app.component.css"]})导出类 AppComponent 实现 OnInit {//获取对 ng-template 占位符标签的引用@ViewChild('placeholder', {read: ViewContainerRef, static: true}) placeholder: ViewContainerRef;构造函数(私有解析器:ComponentFactoryResolver,私有渲染器:Renderer2) {}ngOnInit() {this.createComponent();}创建组件(){//创建 mat-checkbox 标签正文内容let content = this.renderer.createText(' mat-checkbox (dynamic)');//清除任何先前附加的元素或组件this.placeholder.clear();//解析 MatCheckbox 组件并获取工厂类以动态创建组件让工厂 = this.resolver.resolveComponentFactory(MatCheckbox);//创建组件并附加到模板中的占位符让 ref = this.placeholder.createComponent(factory);//设置 mat-checkbox 正文内容(ref.location.nativeElement as HTMLElement).appendChild(content);}}

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

app.module.ts

import { NgModule } from '@angular/core';从'@angular/platform-b​​rowser' 导入 { BrowserModule };从'@angular/forms'导入{FormsModule};从 '@angular/material' 导入 { MatCheckboxModule, MatCheckbox };从 './app.component' 导入 { AppComponent };import { HelloComponent } from './hello.component';@NgModule({进口:[ BrowserModule, FormsModule, MatCheckboxModule ],声明:[ AppComponent, HelloComponent ],//通过将它们包含在 entryComponents 字段中来通知 Angular 那些将动态创建的组件entryComponents: [ MatCheckbox ],引导程序:[ AppComponent ]})导出类 AppModule { }

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

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

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

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).

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.

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

component.html:

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

<div [innerHTML] = "test2">

component.ts:

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

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

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

i.e:

  • category
    • sub category
      • sub of sub category
  • category2

each category or sub-category is <mat-checkbox value="$id"> $title

解决方案

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:

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>

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);
  }
}

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 { }

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天全站免登陆