2017-12-14 1 views
0

나는 초보자이며이 일에 약간의 도움이 필요할 수 있습니다. 우선 무엇을 어떻게 할 수 있는지 보여 주겠다. 내가 어떻게 작동하게 할 것인지 글을 쓸 것이다. 이것은 당신이 선택에 대한 자신의 모습을 원하지 않는만큼 경우에 좋은각 4 자신의 양식 요소 구성 요소

<form> 
     <input name="name" placeholder="name" [(ngModel)]="model.name" value="" /> 
     <select name="select" [(ngModel)]="model.select"> 
     <option value="1">..</option> 
     ... 
     </select> 
     <input type="button" value=" click me" /> 
    </form> 

: 당신이 ngModel 작업 할 때

이 일반적인 방법입니다. 내 목표는이 양식 요소의 미래 디스플레이에 맞게 디자인 할 수있는 div 및 기타 내용을 만들 수있는 구성 요소를 만드는 것입니다. 반면에 ngModel의 편안함을 유지하고 싶습니다. 그래서 템플릿은 내 목표에 다음과 같이한다 : 이미 이런 식으로 뭔가를 만들려고

<form> 
     <input name="name" placeholder="name" [(ngModel)]="model.name" value="" /> 
     <app-select label="label" name="select" [placeholder]="'placeholder'" [(ngModel)]="select" [options]="options"></app-select > 
     <input type="button" value=" click me" /> 
    </form> 

하지만 슬프게도 :( 더 많은 경험을 가지고 어떤 사람이 다음 날 해주십시오 좀 도와 수, 실패 ? https://stackblitz.com/ 다음

+0

당신은 https://stackoverflow.com/questions/46002485/how-can-i-create-my-own-component-for-formcontrols/46002693#46002693을이를 확인 했습니까? 당신의 질문과 비슷한 것 –

답변

0

내가이 양식을 어떻게 내 양식 (I 양식 빌더 반응 형태를 사용하고 마음에없는 유지입니다! 여기에 필요한 경우 사전에 시간 내 주셔서 감사합니다 답변

나는 최소한 뭔가를 다시 만들 수 있습니다 ngModel을 사용한 템플릿 기반 양식) :

처음으로을 작성하고 forms 디렉토리에 사용자 정의 FormModule을 작성합니다.

다음 거기에는 다양한 형태의 구성 요소가 있습니다. 예를 들어 LoginFormComponent을 사용하십시오. 여기

LoginFormComponent입니다 : 여기
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; 
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 

@Component({ 
    selector: 'login-form', 
    templateUrl: './login-form.component.html' 
}) 
export class LoginFormComponent implements OnInit { 
    @Output() onChange: EventEmitter<FormGroup> = new EventEmitter(); 

    form: FormGroup; 

    constructor(private fb: FormBuilder) { 
     this.form = this.fb.group({ 
      email: [null, Validators.email], 
      password: [null, [Validators.required, Validators.minLength(6), Validators.maxLength(60)]] 
     }); 

     this.form.valueChanges.subscribe(() => this.onChange.emit(this.form)); 
    } 

    ngOnInit() { 
     this.onChange.emit(this.form); 
    } 
} 

는 HTML입니다 :

<form autocomplete="off" [formGroup]="form"> 
    <div class="form-group"> 
     <label for="username">Email *</label> 
     <input type="text" id="username" class="form-control" placeholder="Enter your email address" formControlName="email" autofocus> 
     <control-messages [control]="form.get('email')"></control-messages> 
    </div> 

    <label for="password">Password *</label> 
    <input type="password" id="password" class="form-control" placeholder="Enter your password" formControlName="password"> 
    <control-messages [control]="form.get('password')" [label]="'Password'"></control-messages> 
</form> 

이제 FormModule를 가져 모듈 내에 사용자 정의 구성 요소에, 나는 다음과 같은 작업을 수행 할 수 있습니다

app.component.html :

<login-form (onChange)="form = $event"></login-form> 

<button (click)="submit()">Submit</button> 

app.component.ts :

@Component({...}) 
export class AppComponent { 
    form: FormGroup; 

    submit() { 
     // Do something with `this.form`. 
    } 
} 

디자인 이런 종류의 장점은 바로 슈퍼 명확하지 않을 수 있습니다,하지만 몇 가지 할 우리가 수 :

  1. 우선 FormModule을 가져 오는 동안 앱의 어느 곳에서나 login-form 구성 요소를 다시 사용할 수 있습니다. 우리가 그것을 변경하면, 그것은 자동으로 사방에 업데이 트됩니다. 물건을 건조하게 유지합니다.
  2. 다음으로 우리는 동일한 제출 버튼/텍스트가 어디에 있길 원하지 않을 수 있으며, 다른 위치에서 다른 작업을 수행하기를 원할 수 있습니다. login-form 구성 요소에는 양식 자체 만 포함되어 있으며 제출 논리는 그 외부에서 처리됩니다 재사용 능력. 이는 작성 및 편집에 사용되는 양식이있을 때 중요합니다.편집 할 때 버튼을 사용하면 데이터를 저장할 수 있습니다. 생성하는 버튼으로 새로운 것을 만들 수 있습니다. 양식 구성 요소에 제출 단추를 넣으면이 재사용을 쉽게 수행 할 수 없습니다. 이 하나를 제외하고는 LoginFormComponent와 같은 일반적인 생각을 다음과

    import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; 
    import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 
    
    import { Tag } from 'shared'; 
    
    @Component({ 
        selector: 'tag-form', 
        templateUrl: './tag-form.component.html' 
    }) 
    export class TagFormComponent implements OnInit { 
        @Output() onChange: EventEmitter<FormGroup> = new EventEmitter(); 
    
        form: FormGroup; 
    
        constructor(private fb: FormBuilder) { 
         this.form = this.fb.group({ 
          name: [null, Validators.email] 
         }); 
    
         this.form.valueChanges.subscribe(() => { 
          this.onChange.emit(this.form); 
         }); 
        } 
    
        @Input() 
        set tag(tag: Tag) { 
         if (tag) { 
          this.form.patchValue(tag); 
         } 
        } 
    
        ngOnInit() { 
         this.onChange.emit(this.form); 
        } 
    } 
    

    :

  3. 약간 더 복잡한 형태의 경우

, 일부 기본 값을 취할 수있는 형태가,이 예 TagFormComponent에서 살펴 말한다 이 값은 양식의 일부 기본값을 전달할 수 있습니다. 이처럼 :

<tag-form [tag]="tag" (onChange)="form = $event"></tag-form>