Angular - 当ng-template的作用域更改时绑定到formControlName
创始人
2024-10-14 15:00:48
0

要在Angular中使用ng-template的作用域更改时绑定到formControlName,可以使用ng-container来创建一个临时的包装器,并在其中定义ng-template的作用域。以下是一个示例解决方法:

首先,在组件的HTML模板中,使用ng-container来创建一个临时的包装器,并在其中定义ng-template的作用域。将formControlName绑定到ng-container上,而不是ng-template上。

然后,在组件的类中,使用ViewChild装饰器来获取ng-template,并在模板上找到对应的表单控件。

import { Component, ViewChild, TemplateRef } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  myForm: FormGroup;
  
  @ViewChild('myTemplate') myTemplate: TemplateRef;

  constructor(private formBuilder: FormBuilder) {
    this.myForm = this.formBuilder.group({
      myControl: this.formBuilder.group({
        myField: ['']
      })
    });
  }
  
  // 在某个事件中,获取表单控件并做一些操作
  getFormControl() {
    const formControl = this.myTemplate.createEmbeddedView(null).rootNodes[0].querySelector('[formControlName="myField"]');
    console.log(formControl);
  }
}

在上面的示例中,我们使用ViewChild装饰器来获取名为"myTemplate"的ng-template,并在getFormControl方法中找到相应的表单控件。您可以根据自己的需求进行进一步的操作。

请注意,ng-template的作用域更改时,表单控件的绑定也会相应地更新。

相关内容

热门资讯

攻略讲解!pokemmo手机版... 攻略讲解!pokemmo手机版脚本,hhpoker透视脚本视频,解密教程(有挂软件)是一款可以让一直...
分享实测!wepoker有什么... 分享实测!wepoker有什么规律,hardrock作弊,可靠教程(有挂软件)是由北京得wepoke...
交流学习经验!wepoker底... 交流学习经验!wepoker底牌透视,wepoker网页版透视方法,存在挂教程(有挂教程)关于wep...
发现玩家!德普之星辅助器,we... 1、发现玩家!德普之星辅助器,wepoker手机插件,曝光教程(有挂技巧);详细教程。2、德普之星辅...
一起来讨论!德州局透视脚本免费... 一起来讨论!德州局透视脚本免费版下载手机版,wepoker私人局俱乐部,AA德州教程(有挂技巧);致...
技术分享!we poker辅助... 技术分享!we poker辅助器v3.3,aapoker ai插件,详细教程(有挂攻略);亲真的是有...
实测必看!wepoker智能辅... 实测必看!wepoker智能辅助插件,wepoker轻量版透视系统,我来教教你(有挂神器);原来确实...
玩家必看!wepoker私人局... 玩家必看!wepoker私人局外卦,wepoker怎么设置透视,可靠技巧(有挂攻略)是一款可以让一直...
实测发现!wepoker免费透... 实测发现!wepoker免费透视,pokemomo辅助软件,攻略教程(有挂软件)1、点击下载安装,微...
让我来分享经验!wepoker... 让我来分享经验!wepoker智能辅助插件,wepoker辅助透视,曝光教程(有挂方法);《WPK辅...