繁体   English   中英

Angular 从另一个组件发送数据

[英]Angular send data from another component

我想发送从我的另一个组件中选择的数据(文件 .ts 中的变量)

.html :

<div class="liste">
                <select class="form-control" name="Container" (change)="selectChangeHandler($event)">
                    <option disabled selected value> -- select an Container -- </option>
                    <option *ngFor="let v of values;let i = index" [value]="i">
                        {{v.Name}}
                    </option>
                </select>
            </div>

            <div class="tableau" *ngIf="show" >
                <table align="center">
                    <tr align="center"><b>{{selectedValue.Name}}</b></tr>
                    <tr align="center"><td>Matricule: {{selectedValue.Matricule}}</td></tr>
                    <tr align="center"><td>Material: {{selectedValue.Material}}</td></tr>

        <div class="modal-body">
            <app-heat-local> </app-heat-local>
        </div>

如何通过使用在此组件中发送我的数据来获得此组件的价值?

另一个组件 .html (heat-local):

<h6 class="container-name">{{selectedValue.Name}}</h6>

我的文件 .ts :

import {Component, OnDestroy, OnInit} from '@angular/core';
import {Cell} from 'app/data/cell';

@Component({
    selector: 'app-heat-global',
    templateUrl: './heat-global.component.html',
    styleUrls: ['./heat-global.component.css'],
    providers: [HeatService]
})

export class HeatGlobalComponent implements OnInit{

selectedValue = {
        Name: '',
        Matricule: '',
        Material:'',
        Quantity:'',
        Coordonates:'',
    }
    values = [{
        Name: "Container A",
        Matricule: "ABC",

从问题来看,似乎可以通过这种方式解决它。

您可以将所选选项的值设置为selectChangeHandler()内部的属性

selectChangeHandler(event) {
  this.currentValue = event.target.value;
}

将其放入app-heat-local

<div class="modal-body">
  <app-heat-local [value]="currentValue"> </app-heat-local>
</div>

为了能够设定[value]属性,你需要定义@Input()的属性里面HeatLocalComponent

您可以使用@Input()来实现这一点。

import {Component, Input} from '@angular/core';

@Component({
  selector: 'app-heat-local',
  templateUrl: './heat-local.component.html',
  styleUrls: ['./heat-local.component.scss']
})
export class HeatLocalComponent {
  @Input() value: number;
}

要在heat-local.component.html显示值,您可以使用插值

<h6 class="container-name">{{value}}</h6>

您可以阅读有关组件交互的更多信息

更新

要接收名称而不是索引,只需将值从i更改为v.Name {{v.Name}}

或者你可以提供整个对象

<option *ngFor="let v of values;let i = index" [value]="v">
   {{v.Name}}
</option>

请注意您在此处指定的类型。 在上一部分中,指定了number类型,因此除了数字外,它不会带任何其他东西

import {Component, Input} from '@angular/core';

@Component({
  selector: 'app-heat-local',
  templateUrl: './heat-local.component.html',
  styleUrls: ['./heat-local.component.scss']
})
export class HeatLocalComponent {
  @Input() value: string // <== Here you can specify the type by TS type
}

string将仅在选项的值为 string 时使用,如果您想发送整个对象,则将其更改为此@Input() value: any或定义您自己的接口

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM