I am trying to make a Component in Angular 2. This component has a variable title
, whose value is displayed in a part of the template :
import { Component, ViewChild } from '@angular/core';
import { bootstrap } from '@angular/platform-browser-dynamic';
declare var ol: any;
@Component({
selector: 'map',
template: `
<div id="container">
<nav class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<strong class="navbar-brand">{{title}}</strong>
</div>
</div>
</nav>
<div id="down" #mapa style="max-height : 500px;">
</div>
</div>
`
})
class MapaComponent {
@ViewChild('mapa') mapa;
map : any;
title : string = 'Mi mapa';
/* Contructor */
constructor() {}
ngAfterViewInit() {
this.map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: this.mapa.nativeElement,
view: new ol.View({...})
})
}
}
bootstrap(MapaComponent, []); // Component is bootstrapped!
What I want to do is modify the value of said variable for each component created and I was wondering if it could be done in some way by declaring the value of said variable as an attribute of a Component
in the following way:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mapa</title>
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="systemjs.config.js"></script>
<script src="http://openlayers.org/en/v3.12.1/build/ol.js"></script>
<script>
System.import ('built/map')
.then(null, console.error.bind(console));
</script>
</head>
<body>
<!-- Componente creado -->
<map title = "Mapa A"></map>
<link rel="stylesheet" type="text/css" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="http://openlayers.org/en/v3.12.1/css/ol.css" type="text/css">
</body>
</html>
Is it possible to modify the value of the title variable in this way?
you must use the following class ElementRef and so you use it.
index.html
angular.ts
You should only use this with the "components" that start the application, since with the child components if the method you placed above works, the ElementRef class could cause security problems in your web application, check the following links for more information .
Link API angular 2
Problem Documentation
Another solution you can do is to create a child component and thus avoid using unsafe classes.
index.html( without many changes )
start.ts ( We call our new component called MapasComponent )
app/src/frame.html ( We send the options to the child component )
maps.ts (Here we create the maps component, with the "inputs" parameter we send the data)
app/src/maps.html (we print the options)
Cheers!