If I have a component laid out like so
module my.component {
'use strict';
angular.module('example')
.component('customcomponent',
{
templateUrl: 'some/folder/structure/withmyfile.html',
controller: 'componentController',
bindings: {
myBinding: '<'
}
});
}
And the controller, componentController
is designed like this
module my.component {
'use strict';
class ComponentController {
myBinding: string;
$onInit = () => {
console.log(this.myBinding);
};
}
angular.module('example')
.controller('componentController', ComponentController);
}
I'm not able to set my binding inline without using a variable reference it seems. If I call my component in another html file, and try to set the binding's value like this
<customcomponent my-binding="test"></customcomponent>
my goal is that the component would be called, the controller would be executed, and the value, "test"
would pass from the inline declaration in the html, to the variable, myBinding
in the controller.
So that when console.log(this.myBinding);
executes the console should read the word, "test"
and would be of type string.
These are the various ways I've tried to accomplish this, and none so far have worked.
<customcomponent my-binding="test"></customcomponent>
<customcomponent my-binding="\'test\'"></customcomponent>
<customcomponent my-binding="{{test}}"></customcomponent>
<customcomponent my-binding="{{"test"}}"></customcomponent>
<customcomponent my-binding="{{\"test\"}}"></customcomponent>
So is it possible to set the value for the binding inline similar to how one might set the value for a placeholder
attribute?
If you want to bind to a string with a value of test
, use one-way, '<'
, binding with the string quoted:
<customcomponent my-binding="'test'">
</customcomponent>
app.component('customcomponent',
{
templateUrl: 'some/folder/structure/withmyfile.html',
controller: 'componentController',
bindings: {
myBinding: '<'
}
});
Or use attribute, '@'
, binding without quotes:
<customcomponent my-binding="test">
</customcomponent>
app.component('customcomponent',
{
templateUrl: 'some/folder/structure/withmyfile.html',
controller: 'componentController',
bindings: {
myBinding: '@'
}
});
angular.module('app',[])
.component('customcomponent', {
template:
`<div>my-binding={{$ctrl.myBinding}}
</div>`
,
controller: function($scope) {
this.$onInit = () => {
console.log("my-binding=",this.myBinding);
};
},
bindings: {
myBinding: '<'
}
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<customcomponent my-binding="'test'">
</customcomponent>
</body>