angular class and ng-class - javascript

So in Angular you can do this:
ng-class="{ 'my-class': widget.widgetId == '1'}
Which will give the element the class of my-class if the widget.widgetId equals 1.
You can also do this:
class="col-md-{{widget.size}}"
Which will give the element a class of col-md- and then returns whatever widget.size is set to.
However what if I want to do what I'm doing in the second example but with ng-class. For example the following:
ng-class="{ 'col-md-{{widget.size}}': widget.widgetId == '1'}"
I've tried the above with various syntax but it does not seem to work. Is this possible with ng-class?

Here is a basic example of using ng-class:
HTML:
<button ng-class="getLanguageOptionClass(lan)" ng-repeat="lan in language.available" ng-click="language.current=lan">{{lan}}</button>
Javascript
var I18nController = function($scope){
$scope.language = {
current: 'no',
available: ['en', 'no', 'sv', 'da', 'fi']
};
$scope.getLanguageOptionClass = function(language){
return ($scope.language.current==language) ? 'btn btn-primary' : 'btn btn-info';
}
};
Description : getLanguageOptionClass gets called with lan as a parameter, which returns a value which is assigned as a class.
Working example

Not sure wether above will work or not but you can achieve this using by defining a function inside your controller as,
$scope.getClass= function(widget){
var baseClass = "col-md-";
if(widget.widgetId==='1'){
return baseClass + widget.size;
}
}
Inside your html use it like,
ng-class="getClass(widget)"

define a function in controller to get class name processed
$scope.getClassName = function(widgetSize){
return 'col-md-' + widgetSize;
}
call this function from ng-class
ng-class="getClassName(widget.size)"

Related

pass AngularJS value / variable inside javascript

Here is my Angular data (i write here only one data entry as demo, actually i have so many entry):
var font = angular.module('font', []);
font.controller('fontListCtrl', function($scope) {
$scope.font = [
{
id: "_001",
name: "Kalpurush",
download: "1"
}
]
var download = scope.font.download
});
I want to pass my download ID into inside javascript inside html. but i cannot success.
<div class="fontbox" ng-repeat="font in font">
{{font.name}}
<script>ccount_display('download')</script>
</div>
Please help me, thank you :)
I am making some assumption based on your code/question. If that's not the case, I can modify my solution.
There are couple of issues in your code. I've tried to fix them below:
var font = angular.module('font', []);
font.controller('fontListCtrl', function($scope) {
$scope.fonts = [{
id: "_001",
name: "Kalpurush",
download: "1"
}];
//assuming you're accessing above scope variable, your code had 'scope' but not $scope. And it's an array.
$scope.download = $scope.fonts[0].download;
//assuming you want to use download variable in your HTML.
});
Also the HTML is incorrect. You should do something like below:
ng-repeat="font in fonts"
If i understand the problem correctly you want to pass id into the count_display method you can do that by passing font.id and the use of the <script> tag in this context is not necessary. Hope this helps.

what is the equevalant for getelementbyid in angular 2 [duplicate]

I have a code:
document.getElementById('loginInput').value = '123';
But while compiling the code I receive following error:
Property value does not exist on type HTMLElement.
I have declared a var: value: string;.
How can I avoid this error?
Thank you.
if you want to set value than you can do the same in some function on click or on some event fire.
also you can get value using ViewChild using local variable like this
<input type='text' id='loginInput' #abc/>
and get value like this
this.abc.nativeElement.value
here is working example
Update
okay got it , you have to use ngAfterViewInit method of angualr2 for the same like this
ngAfterViewInit(){
document.getElementById('loginInput').value = '123344565';
}
ngAfterViewInit will not throw any error because it will render after template loading
(<HTMLInputElement>document.getElementById('loginInput')).value = '123';
Angular cannot take HTML elements directly thereby you need to specify the element type by binding the above generic to it.
UPDATE::
This can also be done using ViewChild with #localvariable as shown here, as mentioned in here
<textarea #someVar id="tasknote"
name="tasknote"
[(ngModel)]="taskNote"
placeholder="{{ notePlaceholder }}"
style="background-color: pink"
(blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }}
</textarea>
import {ElementRef,Renderer2} from '#angular/core';
#ViewChild('someVar') el:ElementRef;
constructor(private rd: Renderer2) {}
ngAfterViewInit() {
console.log(this.rd);
this.el.nativeElement.focus(); //<<<=====same as oldest way
}
A different approach, i.e: You could just do it 'the Angular way' and use ngModel and skip document.getElementById('loginInput').value = '123'; altogether. Instead:
<input type="text" [(ngModel)]="username"/>
<input type="text" [(ngModel)]="password"/>
and in your component you give these values:
username: 'whatever'
password: 'whatever'
this will preset the username and password upon navigating to page.
Complate Angular Way ( Set/Get value by Id ):
// In Html tag
<button (click) ="setValue()">Set Value</button>
<input type="text" #userNameId />
// In component .ts File
export class testUserClass {
#ViewChild('userNameId') userNameId: ElementRef;
ngAfterViewInit(){
console.log(this.userNameId.nativeElement.value );
}
setValue(){
this.userNameId.nativeElement.value = "Sample user Name";
}
}

How to provide dynamic className to element in React Class render method

I have a ReactClass with name Alert. Its render method returns a div with class alert alert-success or alert alert-error according to the type passed while creating element. I just want to know how to add class based on the type of alert element.
Here is my attempt:
var Alert = ReactClass({
render: function() {
return <div className="alert {this.props.type}">{this.props.message}</div>
}
});
var successAlert = React.createElement(Alert, {
type: 'alert-success'
message: 'Information saved successfully!!'
});
When JSX Template is compiled this.props.type is not converted to the class passed to element. How to achieve this ?
Looks like I have found answer to my question. We can simply do something like this:
var Alert = ReactClass({
render: function() {
return <div className={"alert " + this.props.type}>{this.props.message}</div>
}
});
Just put your classes inside Template evaluators { } in this case. Create your class string based on your props and states.
Hope this is helpful to others.
One way to accomplish this is to have a string which will contain all of your classes and then set it to the Component's className:
var Alert = ReactClass({
var yourClassName = 'alert ';
// Add any additional class names
yourClassName += this.props.type + ' ';
render: function() {
return <div className={yourClassName}>{this.props.message}</div>
}
});
or alternatively you can store your class names in an array and convert it to a class friendly string when you're ready to use it:
var Alert = ReactClass({
var yourClassArray = [];
// Add any additional class names
yourClassArray.push('alert');
yourClassArray.push(this.props.type);
var classString = yourClassArray.join(' ');
render: function() {
return <div className={classString}>{this.props.message}</div>
}
});
Take a look at the classnames package. You can do stuff like this:
className={classNames('alert', `alert-${type}`)}
or
className={classNames({
'alert': true,
'alert-success': success,
'alert-error': error
})
You can use JavaScript template literals
var Alert = ReactClass({
render: function() {
return <div className={`alert ${this.props.type}`}>{this.props.message}</div>
}
});
Your code can be written in following way:
const Alert = ({type, message}) =>
<div className={`alert ${type}`}>{message}</div>
Write in code
className={`form-control-sm d-inline per_player ${"per_player_b_" + index + "_score"}`}
and You will get

Issues with calling function from template

In one case I have a problem with running a function on the Controller from the template. The value becomes a string containing the function signature, not the value that should be returned from the function.
When I use {{ getSomeObject(d) }} in my template markup it works fine, and it prints the object values, meaning that the function got called on the Controller.
I have tried with and without the {{ }}.
Pseudo code:
<div class"xyz" data-lav-fact="getSomeObject(d)"> <!-- Does not work here -->
{{ getSomeObject(d) }} <!-- Works here -->
</div>
And of course the function is added to the scope in the Controller:
$scope.getSomeObject = function(data) {
return { key: "test" };
};
This works in other parts of the application and I don't know what wrong in this case.
Does anyone know what typically can be wrong here?
Since you are trying to set an attribute with a $scope function, you'll need to {{ interpolate }} and use ngAttr attribute bindings. Here is a simple example that shows this in action. Examine the difference between the elements logged out. As you dig, you'll see your { key: 'test' } value being set
<div id="without" data-lav-fact="getSomeObject()">without</div>
<div id="with" ng-attr-data-lav-fact="{{ getSomeObject() }}">with</div>
app.controller('ctrl', ['$scope', function($scope) {
$scope.getSomeObject = function() {
return { key: 'test' };
}
var w = angular.element(document.getElementById('with'));
var wo = angular.element(document.getElementById('without'));
console.log(w[0].attributes); // has value
console.log(wo[0].attributes); // does not have value
}]);
JSFiddle Link

Set $rootScope before textAngular directive initial

I wanna custom textAngular directive options.
The API document says I should set $rootScope.textAngularTools.{customButton} to build a function.
But if I set on controller, directive will tell me property is undefined.
If I set in module.run function, the $rootScope.textAngularTools is undefined.
How do I set the option before directive initialize ?
<text-angular to-toolbar="[['customButton']]">
Setting like this (coffeescript)
$rootScope.textAngularTools.colourRed =
display: "<button ng-click='action()' ng-class='displayActiveToolClass(active)'><i class='fa fa-square' style='color: red;'></i></button>",
action: ->
console.log 'action'
activeState: ->
false
from reading the sources i would suggest you do your configuration in a module run function:
angular.modul('myApp', ['textAngular'])
.run(function($rootScope){
$rootScope.textAngularTools = {
colourRed: {
display: "<button ng-click='action()' ng-class='displayActiveToolClass(active)'><i class='fa fa-square' style='color: red;'></i></button>",
action: function(){
console.log('action);
}
}
};
})
.controller('yourController')...
why should this work? They extends an existing textAngularTools object in their directive:
$rootScope.textAngularTools != null)? $rootScope.textAngularTools : {}

Categories

Resources