2017-12-31 14 views
1

私のプロジェクトは、反応形式に従ってありますインターセプトフォームを送信する方法は?

<form [formGroup]="form" (ngSubmit)="onSubmit()"> 
    <div class="line"> 
    <input class="title" id="title" placeholder="Заголовок вопроса" type="text" formControlName="title"> 
    </div> 

    <div class="line"> 
    <textarea class="question" name="question" id="question" placeholder="Текст вопроса" formControlName="question" cols="30" rows="10"></textarea> 
    </div> 

    <div class="line"> 
    <div class="tags"> 
     <span class="title">Метки</span> 
     <span class="tag" *ngFor="let tag of tags">{{ tag }} <span class="delete" (click)="deleteTag(tag)">X</span></span> 
    </div> 
    <input class="tag" id="tag" placeholder="Введите тег и нажмите enter" type="text" formControlName="tag" #tag (keyup.enter)="addTag($event, tag.value)"> 
    </div> 

    <div class="line"> 
    <button class="btn btn-common" type="submit" mat-button [disabled]="form.invalid"> 
     Отправить 
    </button> 
    </div> 
</form> 

コンポーネントに初期化され、このフォーム:フィールド#tagユーザーの書き込みタグ名を押して

private form: FormGroup; 
    ngOnInit() { 
    this.form = new FormGroup({ 
     'title':  new FormControl('', [Validators.required, Validators.minLength(1)]), 
     'question': new FormControl('', [Validators.required, Validators.minLength(3)]), 
     'tag':  new FormControl() 
    }); 
    } 

は、キーを入力します。そしてフォームは提出です。しかし、私はEnterキーを押した後にフォーム提出をキャンセルする必要があります。

私の試み:

private addTag(event, tag): void { 
    console.log(event); 
    event.preventDefault(); 
    event.stopPropagation(); 

    if(!tag.trim().length) { return; } 

    this.form.patchValue({tag: ''}); 

    if(this.tags.indexOf(tag) === -1) { 
     this.tags.push(tag.trim()); 
    } 
    } 

しかし、これはフォームをsubmiting停止しません。 Enterキーを押した後にフォームをキャンセルする必要があります

+0

私の答えを確認してください。私は実際の例を追加しました – yurzui

答えて

1

keyupイベントが遅すぎます。

私は​​イベント扱いになります。

HTML

(keydown.enter)="addTag($event, tag.value)" 

TS

private addTag(event, tag): void { 
    event.preventDefault(); 
} 

またはあなたがfalse

を返すことができますが

HTML

(keydown.enter)="!!addTag(tag.value)" 
       ^^^^ 
      convert to boolean 

TS

addTag(tag): void { 
    if(!tag.trim().length) { return; } 

    this.form.patchValue({tag: ''}); 

    if(this.tags.indexOf(tag) === -1) { 
    this.tags.push(tag.trim()); 
    } 
} 

Example

関連する問題