【问题标题】:Dynamically load Angular 4 template using existing component and module使用现有组件和模块动态加载 Angular 4 模板
【发布时间】:2018-11-03 22:59:06
【问题描述】:

我正在尝试加载从后端收到的 HTML 模板。此模板包括自定义管道,并且应该填充从不同 Web 服务接收的数据。这是当前设置的示例。

-app
-/person
--person.module.ts
--person.service.ts
--/person-info
---person-info.component.ts

理想情况下,我希望接收模板并将其设置在 person-info.component.ts 中,因为我在该组件中拥有该 HTML 的所有必要代码。我开始按照https://blog.angularindepth.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e 此处解释的流程进行操作,并得出以下结论。

person-info.component.ts

import { JitCompilerFactory } from '@angular/compiler';

export function createJitCompiler() {
  return new JitCompilerFactory([{
    useDebug: false,
    useJit: true
  }]).createCompiler();
}

@Component({
  selector: 'person-info',
  template: `<div #vc></div>`,
  styleUrls: ['./person-info.component.css'],
  providers: [
    {provide: Compiler, useFactory: createJitCompiler},
  ]
})
export class PersinInfoComponent implements OnInit {

@ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;
constructor(
  private route: ActivatedRoute,
  private router: Router,    
  private injector: Injector, 
  private moduleRef: NgModuleRef<any>,
  private compiler: Compiler
)
  ngAfterViewInit() {

this.personService.getPersonTemplate(this.id)
  .then(myTemplate => {  
     const tmpCmp = Component({template: myTemplate})(class{
      });
      const tmpModule = NgModule({declarations: [tmpCmp], imports: [CommonModule]})(class {
      });

      this.compiler.compileModuleAndAllComponentsAsync(tmpModule)
        .then((factories) => {
          console.log('after compiler');
          const f = factories.componentFactories[0];
          const cmpRef = this.vc.createComponent(f);
          cmpRef.instance.name = 'dynamic';
          this.loadData(); // this method just loads data from service
      })
 })
}

这里是接收到的 HTML 代码的 sn-p

person-info.component.html

<div *ngIf="personDataList">
  <div class="panel panel-default">
    <table class="table customBackground results">
      <tr>
        <th>Add</th>
        <th>Full Name</th>
        <th>Id</th>
        <th>Relationship</th>
      </tr>
      <tr *ngFor="let personData of personDataList; let i = index" [class.disabled-background]="changeRowBackground(personData.id)" >
        <td class="form-group">
          <input [attr.disabled]="changeRowBackground(personData.id) ? true : null"  type="checkbox" name="checkbox" ([ngModel])="personData.add" (change)="onSelectAddBox(i)">
        </td>
        <td>{{personData.fullName}}</td>
        <td>{{personData.id}}</td>
        <td>{{personData.rltnType | keyLookup: relTypeList}}</td>
      </tr>
    </table>
  </div>
</div>

<form *ngIf="selectedPersonData" [formGroup]="personForm" (ngSubmit)="onSubmit()">
  <div class="row row-centered">
    <div class="col-md-3 col-centered">
      <label>Add Date</label><span class="required-text">*</span>
      <input  class="form-control" 
              type="text" 
              [formControl]="dateCtrl"
              [(ngModel)]="selectedPersonData.addDate"
              >
      <div *ngIf="dateCtrl.hasError('required') && dateCtrl.touched" class="alert alert-danger">
        Date is required
      </div>
      <div *ngIf="dateCtrl.hasError('errMsg')" class="alert alert-danger">
        {{dateCtrl.getError('errMsg')}}
      </div>           
    </div>
    <div class="col-md-3 col-centered">
      <label>Reason Code</label><span class="required-text">*</span>
       <select  class="form-control" 
                name="code"
                [formControl]="codeCtrl" 
                [(ngModel)]="selectedPersonData.code"
                >
        <option *ngFor="let currCode of codeList; let i = index" [ngValue]="currCode.key">{{currCode.value}}</option>
      </select>
      <div *ngIf="codeCtrl.hasError('required') && codeCtrl.touched" class="alert alert-danger">
        Code is required
      </div>
    </div>
  </div>
</form>
<p><span class="required-text">*</span>Indicates required field</p>
<span>
  <button type="button" class="btn btn-warning btn-sm" (click)="onCancel()">Cancel</button>
  <button type="submit" class="btn btn-success btn-sm" [disabled]="!personForm.valid || !selectedPersonData" (click)="onSubmit()">Submit</button>
</span>

不幸的是,我在尝试这种方法时遇到了问题。主要是绑定Angular语法。我收到如下错误。

Can't bind to 'formGroup' since it isn't a known property of 'form'
Can't bind to 'formControl' since it isn't a known property of 'input'

我目前正在使用 Angular 4

@angular/animations: 4.1.3
@angular/common: 4.1.3
@angular/compiler: 4.1.3
@angular/core: 4.1.3
@angular/forms: 4.1.3
@angular/http: 4.1.3
@angular/platform-browser: 4.1.3
@angular/platform-browser-dynamic: 4.1.3
@angular/router: 4.1.3
@angular/cli: 1.2.5
@angular/compiler-cli: 4.1.3
@angular/language-service: 4.1.3

我想要完成的总体目标是能够根据用户可能拥有的特定安全角色呈现内容。从我所做的研究来看,这似乎是最好的方法,但如果另一种方法更适合这种情况(即使它在较新版本的 Angular 上),请随时告诉我。

【问题讨论】:

标签: angular angular-module angular-compiler


【解决方案1】:

您只需将FormsModule 和ReactiveFormsModule 导入您的自定义模块:

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

const tmpModule = NgModule({
    declarations: [tmpCmp],
    imports: [..., FormsModule, ReactiveFormsModule]
})(class {});

【讨论】:

  • 这解决了我最初遇到的Can't bind to 'formGroup' since it isn't a known property of 'form' Can't bind to 'formControl' since it isn't a known property of 'input' 的问题但是现在,我的表格数据没有被填写。如果我正在调用一个单独的服务来接收数据以填写 HTML,我如何在动态组件中填充该数据?
  • @alberto_g,如果它解决了您的原始问题,您能否接受这个答案并为另一个问题创建一个单独的问题?
猜你喜欢
  • 2017-12-02
  • 1970-01-01
  • 2014-11-23
  • 2018-01-04
  • 2017-11-20
  • 2017-08-27
  • 1970-01-01
  • 2019-05-21
相关资源
最近更新 更多