Franco Rondini
Franco Rondini

Reputation: 11011

How to pass data to nested (child) Angular 2 attribute component

According to http://blog.500tech.com/svg-in-angular-2/ to make inner components of SVG we must use an [attribute] selector:

// svgmap.componet.ts chunk of code: component declaration
@Component({
    selector: '[svgmap]',
    templateUrl: 'app/svg/map/svgmap.template.html'
  })

In my scenario this SVGMapComponent is used in some parent component templates in this way:

    <svg [attr.class]="mapClass[0]" svgmap="1"></svg>
    <svg [attr.class]="mapClass[1]" svgmap="2"></svg>
    <svg [attr.class]="mapClass[2]" svgmap="3"></svg>

So far it works fine but now I need to use the value I tried to pass as the svgmap attribute value (i.e. "1,2,3" in the above example ) into the code of svgmap.componet.ts but I don't know if it is possibile and how to grab it.

If it's possible: what's the syntax I can use in my typescript child component (i.e:svgmap.componet.ts ) ?
If it's not possible: why ? it exists a work around?

P.S.: I read some posts such as https://www.themarketingtechnologist.co/building-nested-components-in-angular-2/ that enlightens in some cases but does not apply to the situation outlined above.

Upvotes: 1

Views: 1361

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209072

You would do it the same way as with a directive: use an @Input() with the same name as the selector

@Component({
  selector: '[svgmap]',
  templateUrl: 'app/svg/map/svgmap.template.html'
})

export class SvgMapComponent {
   @Input('svgmap') value:number;
}
ngAfterContentInit() {
   // this.value is now with value set
   console.log(`SVGMapComponent ngAfterContentInit: level=${this.value}`);
   this.svgClass= `map map--${this.value}`; // example usage of the value
}
// arbitrary code here 
} // end of class 

Upvotes: 2

Related Questions