对象的角度数据绑定私有属性

时间:2018-08-27 13:38:35

标签: angular angular6

此类具有 private 属性和 getter setter 方法。

Season.ts:

export class Season {

  private _seasonId: number;
  private _name: string;  

  get seasonId(): number {
    return this._seasonId;
  }

  set seasonId(value: number) {
    this._seasonId = value;
  }

  get name(): string {
    return this._name;
  }

  set name(value: string) {
    this._name = value;
  }

}

我有一个组件可以显示它:

@Component({
  selector: 'app-season',
  templateUrl: './season.component.html',
  styleUrls: ['./season.component.css']
})
export class SeasonComponent implements OnInit {


  season: Season = new Season();
  seasons: Season[] = [];

 //....

 // There is some stuff to fill 'seasons' array 
  private addSeason(seasonForm: NgForm) {
    if (!this.isUpdateMode) {
      this.addNewMemberToSeasons();
    } else {
      this.editSeasonsMember();
    }
    this.seasonsChange.emit(this.seasons.slice());
    this.resetSeasonForm(seasonForm);
  }

  private editSeasonsMember() {
    const editIndex = this.seasons.findIndex((s) => s.seasonId === this.season.seasonId);
    this.seasons[editIndex] = Object.assign({}, this.season);
  }

  private addNewMemberToSeasons() {
    const clone = Object.assign({}, this.season);
    this.seasons.push(clone);
  }
 // ...

HTML

<li class="list-group-item ..." *ngFor="let season of seasons">
    <div>
      <h6 class="my-0">{{season.name}}</h6>
    </div>
    <span>
            <span class="btn-group-sm" role="group">
              <button type="button" class="btn-sm btn-outline-warning"
                      (click)="editSeason(season.name)">Edit</button>
              <button type="button" class="btn-sm btn-outline-danger"
                      (click)="deleteSeason(season.name)">Delete</button>
            </span>
          </span>
  </li>

将新的季节添加到Seasons数组后,我可以在模板中看到带有按钮的新的空白列表组项目。但是这个季节没有name。而且控制台很清楚。 如果我使用插值绑定是这样的:{{season._name}},则可以正常工作,并且可以在模板上看到name属性。但是这次WebStorm警告我:

ng: Identifier '_name' refers to a private member of 'Season'

如何通过插值绑定渲染具有私有属性的对象?

我正在使用Angular 6。

这里是demo


对不起,为了便于阅读,我没有添加Component的一些重要方法。我更新了方法的问题。实际上,问题出在哪里:

const clone = Object.assign({}, this.season);
this.seasons.push(clone);

感谢user184994。

0 个答案:

没有答案