簡體   English   中英

如何在angular 8中從一個組件到另一個組件獲取文本框的值,反之亦然

[英]How to get the value of text box from one component to other and vice versa in angular 8

我有 2 個組件登錄和主頁。 我想從登錄組件中捕獲文本框的值,並通過單擊登錄組件的繼續按鈕將其傳遞到主頁組件的文本框中。 同樣,我想從 home 組件中捕獲文本框的值,並在單擊 home 組件的繼續按鈕時再次傳遞到登錄組件的文本框中。 這是下面的代碼

登錄.component.html

<div>
<p>Parent Component</p>
<input type="text" [(ngModel)]="inptext">
</div><br>
<button (click)="proceed()">Proceed</button>

登錄.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'; 
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  users:any;
  constructor(private router: Router) { }

  ngOnInit() {
 
  }
 proceed(){
     alert(this.inptext);
     this.router.navigateByUrl('/home');
 }
  
}

主頁.component.html

<div>
<p>Child Component</p>
<input type="text" [(ngModel)]="inptext">
</div><br>
<button (click)="proceed()">Proceed</button>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'; 
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  getListData: boolean = false;
  constructor(private router: Router) { }

  ngOnInit() {

  }
 proceed(){
      
      alert(this.inptext);
       this.router.navigateByUrl('/');
 }
}
  1. 首先你需要在 app.module.ts 中導入 home.component 並在 providers 部分中聲明它

  2. 然后在登錄組件的 login.component 中導入 home.component 然后在構造函數中注入組件public home: HomeComponent

  3. 然后你可以像this.home.variable_name一樣this.home.variable_name所有變量和函數

通過這種方式,您可以將 input 的值分配給 onCLick 方法中調用的函數內的 home 組件的變量

您可以使用@input 和共享服務輕松完成。

//to-login-service.ts

@Injectable({providedIn: 'root'})
export class ToLoginService {
  private data: Subject<string> = new Subject<string>();

  sent(val: string) {
    this.data.next(val);
  }

  get(): Observable<string> {
    return this.data.asObservable();
  }
}

//登錄組件.ts

@Component({
selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  inptext: string;
  passtoHome: string;
  getFromHome: string;

  constructor(private toLoginService: ToLoginService) { }

  ngOnInit() {
    this.toLoginService.get().subscribe(val => {
      this.getFromHome = val;
    });
  }

  proceed() {
    this.passtoHome = this.inptext;
  }
}

//登錄組件.html

<h2>Sent From Home(Child): {{getFromHome}}</h2>

<div>
  <p>Parent Component</p>
  <input type="text" [(ngModel)]="inptext">
</div><br>
<button (click)="proceed()">Proceed</button>


<hr/>

<app-home [pass-from-login]="passtoHome"></app-home>

//home-component.ts

@Component({
selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  inptext: string;
  sentFromLogin: string;

  @Input('pass-from-login')
  set passFromLogin(val: string) {
    this.sentFromLogin = val;
  }

  constructor(private toLoginService: ToLoginService) { }

  ngOnInit() {
  }

  proceed() {
    this.toLoginService.sent(this.inptext);
  }
}

//home-component.html

<h2>Sent From Login (Parent): {{sentFromLogin}}</h2>
<div>
  <p>Child Component</p>
  <input type="text" [(ngModel)]="inptext">
</div><br>
<button (click)="proceed()">Proceed</button>

現在你可以找到這樣的視圖:

在此處輸入圖片說明

您需要使用具有一些標准方式的Component interaction

  1. 使用@output@Input裝飾器進行父子通信。
  2. 使用Shared Service
  3. 使用Observable發出事件
  4. 使用State Managements例如ngrx

有關更多信息,請訪問組件交互

從#1 到#4 的不同方式取決於不同的參數,例如您的Application ScopeState Management Policy等。

在這里你可以簡單地定義一個Shared Service ,它被注入到兩個組件中,並有兩個SetterGetter方法來保持你想要的值。

看這個例子:

共享模型.ts

export interface IItem {
    name: string;
}

共享服務.ts

import { Injectable } from '@angular/core';
import { IItem } from '../entities/iItem';
 
@Injectable()
export class ModelService {
 
    private _items:IItem[] = [];
 
    addItem(item: IItem) {
        this._items.push(item);
    }
 
    getItems(): IItem[] {
        return this._items;
    }
}

組件模板.html

<div>
  <input [(ngModel)]="item.name" placeholder="Item name here..">
  <button (click)="addItem()">Add Item</button>
</div>

組件.component.ts

import { Component } from '@angular/core';
import { ModelService } from '../services/model.service';
import { IItem } from '../entities/iItem';
 
@Component({
  selector: 'create-item',
  templateUrl: './createitem.component.html'
})
export class CreateItemComponent {
 
  private _item:IItem = {name:'',description:'',price:0};
 
  constructor(private _modelService: ModelService){}
 
  public get Item():IItem{
     return this._item;
  }
 
  public addItem(){
     const currentItem:IItem = {
         name:this._item.name,
         description:this._item.description,
         price:this._item.price
     };
 
    this._modelService.addItem(currentItem);
  }
}

ViewComponent.template.html

<div>
  <button (click)="printItems()">Print Item</button>
</div>

ViewComponent.component.ts

import { Component } from '@angular/core';
import { ModelService } from '../services/model.service';
 
@Component({
  selector: 'view-items',
  templateUrl: './viewitems.component.html'
})
 
export class ViewItemsComponent {
 
constructor(private _modelService: ModelService){}
 
 public printItems(){
    console.log('items in warehouse:');
    console.log(this._modelService.getItems());
 }
 
}

有關更多信息和解釋,請訪問此鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM