0

I have a component like this:

import { Component, OnInit,Input } from '@angular/core';

@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() {
  }

}

And in my template:

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

Take a look at the myprop property. In essence assign method has no effect! I was expecting myprop in the template to refer exactly same myprop in the component. I am beginnning to think that as soon as myprop goes out of the component inside the template, it becomes local to the template and doesn't reference the component (original) property.

Any explanation would be great!

beNerd
  • 3,088
  • 5
  • 43
  • 84

3 Answers3

0

showPane is a primitive, thus is immutable. This is more a javascript thing than an angular 2 issue.

you can either set it the template (my favorite)

(click)='showPane = !showPane'

or use an object

//in class
flagsCollection = {showPane:false}

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


// in template
(click)='toggle("showPane")'
yuval.bl
  • 3,566
  • 2
  • 13
  • 28
0

You are assigning the value to wrong property, your property below, only exists in that function:

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

but you want to assign it to myProp instead, which is also the variable you display in your view:

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

Make notice of the keyword this

And if you actually have just one myProp (and not part e.g of iteration), you don't need to pass it to the function, just the new value:

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

assign(value){
  this.myProp = value;
}
Community
  • 1
  • 1
AJT82
  • 60,574
  • 21
  • 115
  • 147
-1

Your toggle method change locally the flag parameter. If you want to update showPane you could try this :

@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>
al37350
  • 139
  • 2
  • 8
  • no i want to have a generic toggle function. so if i have another flag variable like showPane2, I just do toggle(showPane2). – beNerd Mar 01 '17 at 09:45