Angular:ボタンクリックの既存の入力フィールドにテキストを追加する入力とボタンが2つの異なるコンポーネントによってレンダリングされる場所

タンモイ・バタチャルジー

関連する質問
しかし、これはまったく同じではありません。私には2つのコンポーネントがあります。1つのコンポーネントには入力があり、別のコンポーネントにはボタンがあります。次に、別のコンポーネントによってレンダリングされる入力フィールドのボタンをクリックして、テキストを入力します。

input.component.html

<input #input type="text-area"/>

button.component.html

<li (click)="addText($event)">Click Me !!</li>

button.component.ts

@ViewChild('input') private input; addText(event){
    console.log(this.input); //this is undefined 
} 

プロジェクト構造:

  • ./input/input.component.ts
  • ./input/input.component.html
  • ./button/button.component.ts
  • ./button/button.component.html

サービスを使用して、変更を識別するためにサービスをリッスンしてサブスクライブできることはわかっていますが、上記のハイパーリンクで受け入れられた回答がより単純に見えたため、それを避けたかっただけです。

ベガ

リンクの例に基づいて、次の解決策を提案します。2つのコンポーネントは兄弟であるため、を使用@Viewchildして子DOM要素の参照を取得します。@Inputそして、@Outputの通信のために役立ちます。

parent.component.html

   <div class="wrapper">
      <comp1 #comp1 [myText]="name"></comp1>
      <comp2 (clickEvent)="addText()"></comp2>
   </div>

parent.component.ts

  import { ViewChild } from '@angular/core';
  ...

  name = 'Angular'; 

  @ViewChild('comp1') private comp1;

  addText(event) {
    this.comp1.myInput.nativeElement.focus();
    let startPos = this.comp1.myInput.nativeElement.selectionStart;
    let value = this.comp1.myInput.nativeElement.value;
    this.comp1.myInput.nativeElement.value =
      value.substring(0, startPos) + ' rocks! ' + value.substring(startPos, value.length)
  }

button.component.html

  <ul>
     <li (click)="clickEventMethod()"> Click here to add some text </li>
  </ul>

button.component.ts

  import { Output, EventEmitter } from '@angular/core';
  ...
  @Output() clickEvent = new EventEmitter<boolean>();

  clickEventMethod() {
    this.clickEvent.emit();
  }

input.component.html

  <input [(ngModel)]="myText" #myInput type="text" placeholder="Enter some text">`,

input.component.ts

   import { ViewChild, Input } from '@angular/core';
   ...
   @ViewChild('myInput') private myInput;
   @Input() private myText;

デモ

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ