首页 > 解决方案 > 有没有办法从组件内更新 ngModel?

问题描述

我目前正在开发一个 Angular 项目,我的文件最初如下所示:

狗.ts:

export interface Dog {
   name: string;
   age: number;
   breed: string;
}

dog.component.ts:

import { Dog } from '../dog';

@Component({
//setup stuff
})

export class DogComponent implements OnInit {
   dog: Dog = {
      name: "",
      age: 0,
      breed: ""
   };

constructor() {}

method(dog: Dog): void {
   //methods with headers similar to above that use the passed dog object
}

dog.component.html:

<div class="input">
   <div>
      <label for="name">Name: </label>
      <input id="name" [(ngModel)]="dog.name" placeholder="name">
   </div>
   <div>
      <label for="age">Age: </label>
      <input id="age" [(ngModel)]="dog.age" placeholder=0>
   </div>
   <div>
      <label for="breed">Breed: </label>
      <input id="breed" [(ngModel)]="dog.breed" placeholder="breed">
   </div>
</div>

<button class="method" (click)="method(dog)">
   Use Method
</button>

<!--more buttons calling various functions -->

但是,我现在摆脱了 .html 文件中的输入字段,并将它们替换为不同模型的单个输入,如下所示:

dog.component.html:

<div class="input">
   <div>
      <label for="place">Name: </label>
      <input id="place" [(ngModel)]="ranking.place" placeholder="place">
   </div>
</div>

<!-- Same buttons as before -->

然后我创建了一个服务,给定一个排名对象,它将发出一个 GET http 请求并返回一个 dog 对象。所以我现在想在我的 dog.component.ts 文件中创建一个方法,在给定排名时更新狗模型。所以是这样的:

dog.component.ts:

import { Dog } from '../dog';
import { Ranking } from '../ranking';

@Component({
//setup stuff
})

export class DogComponent implements OnInit {
   dog: Dog = {
      name: "",
      age: 0,
      breed: ""
   };

   ranking: Ranking = {
      place: 0,
   };

constructor() {}

updateDogComponenet(ranking: Ranking): void {
   //FILL IN THIS METHOD
   //insert a call to serviceFunction that takes a ranking and returns a dog
   //update the ngModel dog object so that it can be used in other functions
}

method(dog: Dog): void {
   //methods with headers similar to above that use the passed dog object
}

我为所有代码道歉,但如果有人有任何想法,将不胜感激!

标签: javascripthtmlnode.jsangulartypescript

解决方案


我不确定您的应用程序的目的是什么,但解决问题的一种方法是找到逻辑路径。

你必须有一个对狗进行排名的系统,也许你可以在 Dog 类中添加一个“points”或“score”属性。

export class Dog {
   name: string;
   age: number;
   breed: string;
   score: number;
}

然后根据分数,你可以按降序对狗进行排序(得分最多的狗将是第一个)。

在这种情况下,您将不需要 Ranking 类,您可以使用您拥有的 Dog 对象数组并按 score 属性对数组进行排序,然后将其显示在 HTML 中。

我不确定这是否会对您有所帮助,因为我没有您的应用程序的完整上下文,但我让您了解了如何处理该问题。


推荐阅读