在Angular中实例化组件中的类

问题描述 投票:0回答:1

目前有这个

import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core';
import { RsForm } from './rs-form-model/rs-form.model';

@Component({
  selector: 'rs-form',
  templateUrl: './rs-form.component.html',
  styleUrls: ['./rs-form.component.scss'],
  encapsulation: ViewEncapsulation.None
})

export class RsFormComponent {

  @Input() form;

  constructor(){}


  ngOnInit(){
    this.form = new RsForm(this.form);
  }

@Input表单作为json到达。

我想构建一个类的新实例并交给this.form。

有没有办法将JSON交给组件构造函数,以便DI使用JSON数据创建实例?如......

constructor(private form: RsForm){
  this.form // would already have the JSON data attached as well as 
  // RsForm class functions.
javascript angular class
1个回答
0
投票

你能不能这样做,

// import 'RsForm' type here

export class RsFormClass {
  form; // if you know what 'type' it is, specify it
  // and other properties...

  constructor(form: RsForm) { // don't forget to import the RsForm interface type in the import section at the top
    this.form = form;
  }
}

在您的组件中,

// after all the necessary imports including the one for 'RsFormClass'

export class RsFormComponent implements OnInit {

  @Input() form;

  constructor(){}


  ngOnInit(){
    this.form = new RsFormClass(this.form);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.