How to add Class name to Angular2 directive - javascript

I wish to add a class name to NG2 directive in order to apply CSS rules on it. Given the following component:
#Component({
moduleId: module.id,
selector: 'search-form',
templateUrl: 'search-form.component.html',
styleUrls: [ 'search-form.component.css']
})
I tried this:
search-form {
width:100%;
display:block;
}
But it did not work.
How can I add a class to search-form ?

#Component({ // or #Directive({
// use `host:` or `#HostBinding()` (not both)
// host: {'[class.someclass]': 'true'}
})
class SearchFormComponent {
#HostBinding('class.someclass')
someClass = true;
}
Perhaps you mean adding styles to "self" by adding this CSS to search-form.component.css
:host {
width:100%;
display:block;
}

You declare CSS classes in your stylesheet .. search-form.component.css
If you want to target the component in your stylesheet then you could do ...
search-form {
width:100%;
display:block;
}
This will target elements with the tag search-form.
Because Angular2 is component based, it only targets elements inside the component. I am not sure if it will target the actual element itself but I think it will.

I can show an example of this.
Firstly create a stylesheet. like
<style>
.red
{
color:red;
}
.blue
{
color:blue;
}
</style>
Then in your HTML include your style sheet along with angular.min.js and create a dropdown as below.
<select ng-model="a">
<option value="red">red</option>
<option value="blue">blue</option>
</select>
Then create a H1 tag like below.
<h1 ng-class="a">Header color</h1>
Note. HTML has to be within the div of ng-app you create.
Hope this helps. All the best.

Related

Preserve the whitespaces of an element while using *ngFor

I am using Angular.js, *ngFor for looping over the array and display the values. I want to preserve the spaces of an elements like array is,
string arr1 = [" Welcome Angular ", "Line1", "Line2", "
Done "]
I have used :
<div *ngFor="let arrValue of arr1">
{{arrValue}}
</div>
current output:
Welcome Angular
Line1
Line2
Done
Expected output:
Welcome Angular
Line1
Line2
Done
How to preserve the spaces of an elements like array without any modification.
Here, link for stackblitz where displaying by looping over. You can perform practical and Please let me know if you figure out way to preserve element with white spaces.
Thank you in advance.
https://stackblitz.com/edit/ngfor-examples?file=app%2Fapp.component.ts,app%2Fapp.component.css
Use the css style white-space: pre;
css
.preserve-whitespace {
white-space: pre;
}
ts
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
arr1 = [' Welcome Angular ', 'Line1', 'Line2', ' Done '];
name = 'Angular';
}
html
<div *ngFor="let arrValue of arr1" class="preserve-whitespace">
{{ arrValue }}
</div>
forked stackblitz
You could try this
<div *ngFor="let arrValue of arr1">
<pre>{{arrValue}}</pre>
</div>
Similar to all the answers above you can use CSS's white-space: pre-wrap; to accomplish this goal. You can either do it inline which would look like this:
yourComponent.html
<div style="white-space: pre-wrap;">
Or you could add a CSS attribute to the div you want like so:
styles.scss
.white-space {
white-space: pre-wrap;
}
yourComponent.html
<div class="white-space">
Try the following:
<div *ngFor="let arrValue of arr1">
<pre>
{{arrValue}}
</pre>
</div>

How to style encapsulated child components in angular?

How to style encapsulated child components in angular?
Following are the child and parent components with view encapsulation enabled.
** child
//template
<div class="child-container"> </div>
// class
#Component({
selector: "app-child",
templateUrl: "./child.component.html",
styleUrls: ["./child.component.css"],
encapsulation: ViewEncapsulation.ShadowDom
})
** parent
//template
<div class="parent-container"> </div>
// class
#Component({
selector: "app-parent",
templateUrl: "./parent.component.html",
styleUrls: ["./parent.component.css"],
encapsulation: ViewEncapsulation.ShadowDom
})
How can I select a particular class inside the Child component from the parent component's stylesheet and change it's style?
** parent
//template
<div class="parent-container">
<app-child></app-child>
</div>
// class
#Component({
selector: "app-parent",
templateUrl: "./parent.component.html",
styleUrls: ["./parent.component.css"],
encapsulation: ViewEncapsulation.ShadowDom
})
//styles
app-child {
.child-container {
background colour: red;
}
}
Currently when I try to select a class from the child component, I'm not being able to override it's styles. Please help!
Remember that ViewEncapsulation.ShadowDom is required for my used cased. So we have to keep that in mind.
css variables are accessible through the shadow dom..
so in your app-parent component scss, you should be able to do something like
--child-comp-background: red;
and in your app child component scss,
background-color: var(--child-comp-background, white) //white is a default incase the variable isnt defined or passed down from the parent
you can use :host-context() to do that
:host-context(.parent-container) .child-container{
...style here
}
Here the demo: Demo

Add border and background color when I click the yes button

I am developing a kind of text boxes for comments.
When I click on the YES button I would like the box where the click came from, to have some kind of borders and a background color in order to signal that the click came from that box.
Can someone help me?
BLITZ
code
<div class="Submitcomments" *ngFor="let c of data; let i = index;">
<div>
<div class="row rowComments" style="margin-top: 11px;">
</div>
<div class="form-group">
<textarea #myinput type="text" class="form-control AreaText" rows="2"></textarea>
</div>
<div class="row" style="margin-top: -20px; margin-left: 5px;">
<button *ngIf="c.currentState=='pause'" class="btn reply" (click)="adjustState(i)">Yes</button>
<button *ngIf="c.currentState=='start'" class="btn reply1" (click)="adjustState(i)">No</button>
</div>
</div>
</div>
Try to use the [ngStyle] binding in your html.
Something like this:
<textarea #myinput type="text" class="form-control AreaText" rows="2"
[ngStyle]="{
'background-color': c.currentState=='start' ? '#daf4d5' : 'initial',
'border': c.currentState=='start' ? '1px solid green' : ''
}">
</textarea>
There are shorter ways to write the ngStyle but this one allows you to choose a style for box elements that aren't clicked too.
Also, you might want to move the ngStyle value in your component as a string, and use that instead (to make the html more readable).
You can use use AfterViewInit to wait until the component has loaded. Then just update each textarea styles everytime the child btn is clicked inside of each element .Submitcomments.
import { Component, ViewChild, ElementRef, AfterViewInit } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
ngAfterViewInit() {
let submitComments = document.querySelectorAll('.Submitcomments');
[].slice.call(submitComments).forEach((submitComment, index) => {
submitComment.querySelector('.btn').addEventListener('click', (event) => {
submitComment.querySelector('textarea').style.border = '1px solid red';
});
});
}
https://stackblitz.com/edit/angular-qe9hac?file=src/app/app.component.ts
NOTE: I'm not an angular 2 developer, so I'm sure there is a more "angular" type of way to do this. But this works for now.
try this also don't forget to upvote me if this is what you need becuse this takes time for me to do and i dont have time wasting to do this alot but if this isnt working at all you dont have to upvote me im just saying if it works remember to upvote me
window.onload = function() {
//onclick event
document.getElementById("yes").onclick = function fun() {
var element = document.getElementById("yes");
element.classList.add("yeep");
element.classList.remove("unk");
}
}
.yeep{
background-color:green ;
border-color:limegreen ;
border-width:5px;
color:white;
}
.unk{
background-color:darkgray;
border-color:gray;
border-width:5px;
color:white;
}
<button class='unk' id = 'yes'>yes!</button>

How can I style a component whose class changes based on a `use` directive in Svelte?

I am creating a directive which adjusts the class of the element that it is applied to. However, the styles for that class do not apply when the class changes. For instance:
Form.svelte
<form id='sign-in' use:delayed={ handleSubmit }>
<label for='sign-in-name'>Your Name</label>
<input required id='sign-in-name' type='text' />
<input type='submit' value='Sign In' />
</form>
<style>
form {
display: block;
}
form.submitting {
display: none;
}
</style>
Delayed.js
export default function(node, action) {
node.addEventListener('submit', async function(event) {
event.preventDefault()
const originalClass = node.className
node.className = `${ originalClass } submitting`
await action()
node.className = originalClass
})
}
In this case, the class will change successfully in the DOM, but the form will still display. The form.submitting style doesn't even make it into the CSS generated by Svelte.
I know that I can work around this using a global stylesheet, but I'm curious why the scoped styles don't apply and if there's a way to make it work that way.
This works, but it feels hacky.
<style>
form {
display: block;
}
:global(form.submitting) {
display: none;
}
</style>
Svelte compiler removes unused CSS rules, that is rules with selectors that do not match in the markup of the component. You should have a compiler warning "Unused CSS selector" about that. And since the compiler can't see dynamically added classes, your form.submitting selector is removed.
The solution is indeed to make your dynamic selector :global(...).
If you want your style to only apply in the scope of this component and its children, you need a wrapping element that you can reference like such:
<div>
<form>...</form>
</div>
<style>
div :global(form.submitting) { ... }
</style>
Svelte will scope the div part of the selector to the current component, effectively meaning that the :global(...) part will only apply to the form inside a <div> inside this component.

Asp.Net MVC overriding Class CSS

I have an H1 tag and inside that, there is anchor tag which is generating from the code
<div class=".slide-title">
<H1>
#RenderLinkTracking(m => m.btn, Model.bTnTitle)
</H1>
</div>
The RenderLinkTracking creates anchor tag
Image Title
CSS of the anchor tag is
.slide-title a
{
color : red;
}
I am trying to override the CSS of the anchor tag. This is how I am doing and working fine
<style>
#if (Model.Param.H1CSS!= null)
{
<text>
.slide-title a
{
#Html.RenderCSSAndJSAttributes(Model.Param.H1CSS).ToString().Replace("style=","")
}
</text>
}
</style>
The method Html.RenderCSSAndJSAttributes is generating a style color:#001595 !important;font-family:Book Antiqua !important;Text-align:10px;Text-align:Center
Is there any better way to override the class CSS or append the inline CSS using jquery? Any suggestion would be appreciated.
Thanks in advance
Change custom helper could look like this:
namespace System.Web.Mvc {
public static class HtmlHelperExtensions {
public static MvcHtmlString RenderLinkTracking(this HtmlHelper helper, string url, string linkText, string style) {
//...
return MvcHtmlString.Create(String.Format("<a href='{0}' style='{1}'>{2}</a>", url, style, linkText));
}
}
}
So You can pass style for each custom link like this:
<div class=".slide-title">
<H1>
#RenderLinkTracking(m => m.btn,Model.yourUrl, Model.bTnTitle, Model.Param.H1CSS)
</H1>
</div>
Simple Solution is by creating another CSS Style for the anchor hierarchy .slide-title h1 a
.slide-title a
{
color:#001595!important;
}
.slide-title h1 a
{
color: green!important;
}
<div class="slide-title">
<h1>
H1 Anchor
</h1>
Simple Anchor
</div>

Categories

Resources