Angular 2设置默认表单控件值表示组件

时间:2017-04-07 07:09:18

标签: angular ngrx

我有点迷失在这里。我有一个使用商店架构(ngrx)构建的角度2应用程序,并使用智能和演示组件。

在存储和检索数据方面,一切都运行良好,但在设置表示组件中的默认表单控件值时,我感到困惑。它一直无法编译,因为该属性不存在,这显然是一个时间问题,因为当它首次尝试加载表单时该属性不存在。

因此,只有在@Input()客户值可用后,如何在表单控件中设置默认值或初始值。

演示文稿组件

    import { Component, OnInit, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators, FormControl } from "@angular/forms";

// Mojito Models
import { CustomerModel } from '../../models/customer-model';

@Component({
  selector: 'mj-customer-detail',
  templateUrl: './customer-detail.component.html',
  styleUrls: ['./customer-detail.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CustomerDetailComponent implements OnInit {

  @Input() customer: CustomerModel;
  @Output() showView: EventEmitter<string> = new EventEmitter<string>();

  customerForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {

    this.customerForm = this.fb.group({
      name: [this.customer.name, Validators.required],  // This fails to compile
      overview: ['', Validators.required],
      imagePath: ['', Validators.required]
    });

  }

}

模板

{{customer?.name}} **// This works fine it displays the customer name**

<form [formGroup]="customerForm"  (ngSubmit)="onSaveCustomer(contact)">

    <md-card class="demo-card demo-basic">
        <md-card-content>
            <br>
            <table style="width: 100%" cellspacing="0">
                <tr>
                    <td>
                        <img [src]="imagePath.value" class="card-image">
                    </td>
                    <td>
                        <md-input-container style="width: 100%">
                            <input mdInput placeholder="Image Url" style="width: 100%" formControlName="imagePath" type="text" id="imagePath" #imagePath/>
                        </md-input-container>
                    </td>
                </tr>
            </table>

            <md-input-container style="width: 100%">
                <input mdInput placeholder="Name" style="width: 100%" formControlName="name" type="text" id="name" #name/>
            </md-input-container>
            <md-input-container style="width: 100%">
                <input mdInput placeholder="Overview" style="width: 100%" formControlName="overview" type="text" id="overview" #overview/>
            </md-input-container>

        </md-card-content>
    </md-card>

</form>

SMART COMPONENT

客户组件

import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";

// 3rd Party Modules
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';

// Mojito Components
import { ApplicationState } from '../../store/application-state';
import { CustomerEffects } from '../../store/effects/customers.effects';
import { ADD_CUSTOMER_SUCCESS, getCustomers, addCustomer, CustomerSelected } from '../../store/actions/customer.actions';
import { CustomerModel } from '../models/customer-model';


@Component({
  selector: 'mj-customer',
  templateUrl: './customer.component.html',
  styleUrls: ['./customer.component.scss']
})
export class CustomerComponent implements OnInit {

  customers$: Observable<CustomerModel>;
  customer$: Observable<CustomerModel>;
  addCustomerSuccess$ : Observable<any>;
  showView: string = 'list';

  constructor(private router: Router, private store: Store<ApplicationState>, private customerEffects : CustomerEffects) {

    this.store.dispatch(getCustomers());
    this.customers$ = store.select("customers");
    this.customer$ = store.select("customer");

    this.addCustomerSuccess$ = this.customerEffects.addCustomer$.filter(( { type } ) => type === ADD_CUSTOMER_SUCCESS);

  }

  addCustomer( customer: CustomerModel ) {

    this.store.dispatch(addCustomer(customer));

  }

  ngOnInit() {


  }

  onSelectedCustomer(selectedCustomerId){

    this.store.dispatch(CustomerSelected(selectedCustomerId));

  }

  changeView(viewType){

    this.showView = viewType;

  }

}

客户模板

<mj-customer-detail (showView)="changeView($event)" [hidden]="showView!='detail'" [customer]="customer$ |async"></mj-customer-detail>

1 个答案:

答案 0 :(得分:2)

获取值时只需更新表单:

  ngOnChanges() {
    if(this.customer) {
      this.customerForm.get('name').setValue(this.customer.name);
    }
  }

  ngOnInit() {
    this.customerForm = this.fb.group({
      name: [null, Validators.required],  // This fails to compile
      overview: ['', Validators.required],
      imagePath: ['', Validators.required]
    });
  }