使用表格在Angular 5中创建带有子组件的对象

时间:2018-07-03 17:37:05

标签: angular typescript

我正在构建一个表单来创建account

帐户模型包含一个address组件。

地址具有其自己的模型。

如何创建一个新的account对象,该对象在前端具有完全实例化的address组件?

account-create.component.html

<form [formGroup]="newForm" (ngSubmit)="createAccount()">
    <div class="form-group" [ngClass]="{'has-error': newForm.get('name').errors && newForm.get('name').touched}">
        <input type="text" class="form-control" placeholder="Account Name" formControlName="name">
        <span class="help-block" *ngIf="newForm.get('name').hasError('required') && newForm.get('name').touched">
            Account name is required
        </span>
    </div>

    //address portion goes here

    <div class="form-group text-center">
        <button class="btn btn-success" type="submit">Register</button>
    </div>
</form>


account-create.compoent.ts

import...

@Component({
  selector: 'app-account-create',
  templateUrl: './account-create.component.html',
  styleUrls: ['./account-create.component.css']
})

export class AccountCreateComponent implements OnInit {
  @Output()
  cancelCreateNew = new EventEmitter();
  account: Account;
  newForm: FormGroup;

  constructor(
    private accountService: AccountService,
    http: HttpClient,
    @Inject("BASE_URL") baseurl: string,
    private router: Router,
    private alertify: AlertifyService,
    private fb: FormBuilder
  ) { }

  ngOnInit() {
    this.createNewForm();
  }

  createNewForm() {
    this.newForm = this.fb.group({
      name: ["", [Validators.required]]
      //address???
    });
  }

  createAccount() {
    this.account = Object.assign({}, this.newForm.value);
    this.accountService.createAccount(this.account).subscribe(() => {
      this.alertify.success("Account creation successful");
      },
      error => {
        this.alertify.error(error);
      },
      () => {
        this.router.navigate([`/accounts/${this.account.id}`]);
      });
  }
}


_models \ account.ts

import { Address } from "./address";

export interface Account {
  id: number;
  name: string;
  address?: Address;
}


_models \ address.ts

export interface Address {
  id: number;
  addressLine1: string;
  addressLine2?: string;
  addressLine3?: string;
  city: string;
  state: string;
  zip: string;
}

1 个答案:

答案 0 :(得分:0)

回想起来,这很容易。这是我在项目中的操作方式:

private convertFormToSong(rawSong: {owner: string, title: string, composer: string, \
    key: string, data: string, meta: string}): Song {
      return new Song(rawSong.owner, rawSong.title, rawSong.composer, rawSong.key, \
          JSON.parse(rawSong.data), JSON.parse(rawSong.meta));
  }

然后,您这样称呼它:

updateSong(index: number, newSong: FormGroup) {
    const song = this.convertFormToSong(newSong.value);
    ...

那是由于这个电话:

onSave() {
    if (this.editMode) {
      this.songsService.updateSong(this.id, this.songForm);
    } else {
      this.songsService.addSong(this.songForm);
    }
    this.onCancel();
  }

从中捕获的动作:

<form [formGroup]="songForm" (ngSubmit)="onSave()">