父级更改时传递数据 angular 7

Pass data on parent change angular 7

我有两个下拉列表,当两个下拉列表中的任何一个发生变化时,我需要将它们的两个值都传递给组件中的 updateGraph 函数

   <div class="card-body" (change)="updateGraph($event)">
                        <div class="row">
                            <label>City</label>
                            <select data-id="selects1" class="browser-default custom-select">
                                <label>City</label>
                                <option selected>Select a city</option>
                                <option *ngFor="let city of cities" [value]="city">{{ city }} </option>
                            </select>
                        </div>
                        <div class="row">
                            <label>Scale</label>
                            <select data-id="selects" class="browser-default custom-select">
                                <option selected>Scale</option>
                                <option *ngFor="let scale of scales" [ngValue]="scale.value">{{ scale.Name }}
                                </option>
                            </select>
                        </div>
                        <div class="row">
                            <mdb-date-picker name="mydate" [options]="myDatePickerOptions" [placeholder]="'Selected date'"
                                [(ngModel)]="model" required></mdb-date-picker>
                        </div>
                    </div>

我认为问题出在

(change)="updateGraph($event)"

被放置在 div 元素上,因为 divs 没有 onChange 事件,除非卡体以某种方式提供。

我会将调用移至两个 select 元素,因此它会在 select 的任一 onChange 事件中触发。

您也可以传入任何您需要的变量,或者只是从 .ts 文件中引用它们。

选项 #1 看起来像,将其移动到 selects,然后使用:

(change)="updateGraph(city, scale.Name)"

.ts 文件上的选项 #2 您可以在 updateGraph 函数中引用 this.citythis.scale.Name

但要确保(更改)在两个 select 元素上

您必须在两个 select 元素上应用 updateGraph,如下所示

<select data-id="selects1" (change)="updateGraph($event.target.value)"> class="browser-default custom-select">
                                <label>City</label>
                                <option selected>Select a city</option>
                                <option *ngFor="let city of cities" [value]="city">{{ city }} </option>
                            </select>

如果你想绑定一个属性 like id as value

<option *ngFor="let city of cities" [value]="city.id">

所以 $event.target.value 将是 selected id

如果你想对两个下拉菜单重用相同的方法,只需传递一些常量值作为参数

 updateGraph('scale',$event.target.value)  //for scale 
 updateGraph('city',$event.target.value) //city

您可以从组件中检查条件

updateGraph(type,value){
if(type==='scale'){
  //value for scale 
}
else if(type==='city'){
//value for city
}
}

Stackblitz Demo