通过模板更改组件属性的值

时间:2017-03-01 09:32:53

标签: javascript html angular

我有这样的组件:

从' @ angular / core'中导入{Component,OnInit,Input};

@Component({
  selector: 'topic-details',
  templateUrl: './detailpane.component.html',
  styleUrls: ['./detailpane.component.scss']
})
export class DetailpaneComponent implements OnInit {
  @Input() topics;
  myprop;
  constructor() { }
  assign(property,value){
      property = value;
  }
  ngOnInit() {
  }

}

在我的模板中:

<button (click)='assign(myprop,"some value")'>testing</button>
{{myprop}}

看一下myprop属性。本质上,assign方法没有效果!我期待模板中的myprop在组件中引用完全相同的myprop。我开始认为,只要myprop退出模板中的组件,它就会变成模板的本地,并且不会引用组件(原始)属性。

任何解释都会很棒!

3 个答案:

答案 0 :(得分:0)

showPane是一个原语,因此是不可变的。 这是一个javascript的东西比角度2的问题。

您可以将其设置为模板(我最喜欢的)

(click)='showPane = !showPane'

或使用对象

//in class
flagsCollection = {showPane:false}

toggle(flag){
  this.flagsCollection[flag] = !this.flagsCollection[flag];
}


// in template
(click)='toggle("showPane")'

答案 1 :(得分:0)

您要将值分配给错误的属性,您的property位于该属性中仅存在:

assign(property,value){
  property = value;
}

但您希望将其分配给myProp,这也是您在视图中显示的变量:

assign(property,value){
  this.myProp = value;
}

注意关键字this

如果你实际只有一个myProp(而不是迭代的一部分),你不需要将它传递给函数,只需要传递给新函数:

<button (click)='assign("some value")'>testing</button>

assign(value){
  this.myProp = value;
}

答案 2 :(得分:-1)

您的切换方法会在本地更改flag参数。如果你想更新showPane,你可以试试这个:

@Component({
  selector: 'topic-details',
  templateUrl: './detailpane.component.html',
  styleUrls: ['./detailpane.component.scss']
})
export class DetailpaneComponent implements OnInit {
  @Input() topics;
  showPane = false;
  constructor() { }
  toggle(){
      this.showPane = !this.showPane;
  }
  ngOnInit() {
  }

}

<div class="col-md-12 list-group topics" [ngClass]="{'topics-small':showPane}" >
   <a  class="list-group-item cursor-pointer"

   *ngFor='let topic of topics' 
   (click)='toggle()'
   >{{topic.name}}</a>>

</div>