2016-07-14 1 views
12

이의 나는 다음과 같은 유형의 Mailtype의 타이프 스크립트 객체가 있다고 가정 해 봅시다 모델의 속성에 대한 참조 링크 의 "속성"필드는 type 속성의 배열 인 경우 : 내 구성 요소의 현재Angular2 사용 [(ngModel는)] [ngModelOptions] = "{독립형 : TRUE}"로 :</p> <pre><code>export class Mailtype { constructor( public name?: string, public locale?: string, public email?: string, public properties? : Property[] ) { } } </code></pre> <p>을

export class Property { 
    constructor(
    public name?: string, 
    public type?: string, 
    public example?: string, 
    public required?: boolean, 
    public masked?: boolean 
) { } 
} 

가 나는 하나의 Mailtype 개체가와 HTML을 편집하고 Mailtype의 속성 배열에 추가하는 데 사용되는 폼 요소가 있습니다 :

,210
<form> 
    <tr *ngFor="let property of model.properties; let i=index"> 
      <td> 
      <input type="text" [(ngModel)]="property.name" required> 
      </td> 
    </tr> 
    <button (click)="onAddProperty()">Add property</button> 
</form> 

성분 :

export class MailtypeComponent { 
    model : Mailtype; 
    constructor() { 
    this.model = new Mailtype('','','',[]); 
    this.model.properties.push(new Property()); 
    } 

    onAddProperty() { 
    this.model.properties.push(new Property()); 
    } 
} 
I 특히 동일한에서 [(ngModel)은, 배열의 배열 요소를 기준으로 "속성"을 연결 사용할 수 게 아니라면 궁금

배열을 반복 할 때가 언제입니까? 그것은 위의 코드에 대해 다음과 같은 오류가 발생하기 때문에 :

ORIGINAL EXCEPTION: If ngModel is used within a form tag, either the name attribute must be set 
         or the form control must be defined as 'standalone' in ngModelOptions. 

         Example 1: <input [(ngModel)]="person.firstName" name="first"> 
         Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}"> 

을 그래서 제안이야 나도 [ngModelOptions]="{standalone: true}"를 사용하거나 HTML에 이름 필드를 추가합니다. 이 경우에는 [ngModelOptions]="{standalone: true}"처럼 보입니다. standalone: true은 실제로 그것에 관한 문서를 찾을 수 없기 때문에 실제로 의미가 있습니까?

답변

38

<form> 태그를 사용할 때 @angular/forms을 사용하면 자동으로 FormGroup이 생성됩니다. 모든 들어

ngModel 그것이 FormControl를 생성하고 위에서 만든 FormGroup에 추가됩니다 <input> 태그 포함; 이 FormControlname 속성을 사용하여 FormGroup에 이름이 지정됩니다.

예 :

<form #f="ngForm"> 
    <input type="text" [(ngModel)]="firstFieldVariable" name="firstField"> 
    <span>{{ f.controls['firstField']?.value }}</span> 
</form> 

이 말했다, 질문에 대한 답은 다음과 같습니다.

standalone: true으로 표시하면이 문제가 발생하지 않습니다 (FormGroup에 추가되지 않음).

참조 : 나를 위해 https://github.com/angular/angular/issues/9230#issuecomment-228116474

6

코드 :

<form (submit)="addTodo()"> 
 
    <input type="text" [(ngModel)]="text"> 
 
</form>

오류가 발생합니다,하지만 난 입력에 이름 속성을 추가 :

<form (submit)="addTodo()"> 
 
    <input type="text" [(ngModel)]="text" name="text"> 
 
</form>

그리고 작동하기 시작했습니다.

-1

양식 내의 모든 구성 요소 또는 컨트롤은 이름이어야하며 소수, ngBootstrap과 같은 외부 컨트롤러 여야합니다.

ExamplePrimeNg

관련 문제

 관련 문제