【问题标题】:Why ngClass does not work?为什么 ngClass 不起作用?
【发布时间】:2018-02-26 07:29:19
【问题描述】:

我有一个父组件和一个子组件:

父 JS

export class ListComponent {
  public users = [{Id: 1, Name: 'One'}, {Id: 2, Name: 'Two'}, {Id: 3, 
Name: 'Three'}];
  public selected = [{Id: 2, Name: 'Two'}];}

父 HTML

my-child([users]="users", [selected]="selected")

子 JS

export class ChildComponent {

@Input() public users: string[];

@Input() public selected: string[];

public isSelected(user.Name) { 
  return this.selected.indexOf(user) !== -1;
}

public clickOnUser(user.Name) {
  if (this.selected.indexOf(user.name) !== -1) {
      this.selected.splice(this.selected.indexOf(user.Name), 1);
    } else {
      this.selected.push(user.Name);
    }
  }

}

子 HTML

div(*ngFor="let user of users")
  p(
    [ngClass]="{ selected: isSelected(user.Name) }", 
    (click)="clickOnUser(user)") {{user.Name}}

我需要默认选择列表中的第二项(为此,我的 SASS 文件中有一个“已选择”类)。目前 IDE 中存在错误:

"public isSelected(user.Name) {" - 点被突出显示,因为需要逗号。

"public clickOnUser(user.Name) {" - 同样的错误。

Here 我们可以看到几乎相同的示例,并且工作正常(这种情况下的区别在于数组 - 它们不包含对象)。 那么,如何让我的列表中的第二项默认被选中呢?

【问题讨论】:

    标签: angular


    【解决方案1】:

    您需要做的就是:

    user.Nameuser 在您的 TemplateComponent

    默认情况下未选择第二个对象的解决方案

    export class ParentComponent {
      public users = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3, name: 'three'}];
      public selected = [];
    
      constructor(){
        this.selected.push(this.users[1]);
      }
    }
    

    这背后的原因很有趣How to determine equality for two JavaScript objects?

    根据文档 indexOf

    indexOf() 使用 strict 比较 searchElement 和 Array 的元素 相等(与 === 或三等号运算符使用的方法相同)。

    WORKING DEMO(带数组存储对象)


    欲了解更多详情,请运行以下代码段:

    var a = {Id: 2, Name: 'Two'};
    var b = {Id: 2, Name: 'Two'};
    var c = a;
    
    console.log('Same Obejct But not equal (Not Strickly) --> ' ,a==b);
    console.log('Same Obejct But not equal (Strickly) --> ',a===b);
    console.log('But Here it will work cause of refernce --> ',a==c);
    console.log('Same for Strickly --> ',a===c);

    【讨论】:

    • 谢谢,但是如何让第二个元素默认选中呢?它应该是红色的。顺便说一句,在您的 plunker 点击工作正常,但如果我点击本地应用程序元素中的元素保持黑色。
    • 抱歉,点击按预期工作。但是第二个元素还是默认没有选中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 2019-08-06
    • 2016-07-05
    相关资源
    最近更新 更多