The design of Angular2 components is influenced by the CSS styles set within their containers

If I have a component named MyComponent with a table in its view

        <table>
            <thead>
                <tr>
                    <th class="col1">COL1</th>
                    <th class="col2">COL2</th>
                    <th class="col3">COL3</th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="#item of items">
                    <td class="col1">{{item.content1}}</td>
                    <td class="col2">{{item.content2}}</td>
                    <td class="col3">{{item.content3}}</td>
                </tr>
            </tbody>
        </table>

I want to place MyComponent inside different containers (e.g. Container1 and Container2) and set specific attributes for the table (like column width) using CSS files attached to the containers. For example, in Container1, CSS file could be defined as:

.col1 {
    width: 40%;
}
.col2 {
    width: 30%;
}
.col3 {
    width: 30%;
}

And in Container2, a different CSS file with different attributes could be used. Is this achievable? Thank you

Answer №1

To implement this functionality, you can utilize the ngStyle and Input.

The structure of the MyComponent would look like this:

@Component({
  selector:'table-component',
  template:`
    <table>
      <thead>
        <tr>
          <th [ngStyle]="col1css">COL1</th>
          <th [ngStyle]="col2css">COL2</th>
          <th [ngStyle]="col3css">COL3</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="#item of items">
          <td [ngStyle]="col1css">{{item.content1}}</td>
          <td [ngStyle]="col2css">{{item.content2}}</td>
          <td [ngStyle]="col3css">{{item.content3}}</td>
        </tr>
      </tbody>
  </table>`
})
export class MyComponent{
  @Input() col1Css;
  @Input() col2Css;
  @Input() col3Css;
}

Subsequently, in the container components:

@Component({
    selector: 'container1',
    directives:[MyComponent],
    template: `<table-component [col2Css]="col2Css" [col3Css]="col3Css" [col1Css]="col1Css"></table-component>`
})
export class Container1 {
  col1Css = {'width':'40%'};
  col2Css = {'width':'30%'};
  col3Css = {'width':'30%'};
}

You can view an example of implementation on Plunker

Answer №2

If you have multiple .css files, one approach is to utilize the styleUrls property within the @Component decorator which can accept an array of strings. Keep in mind that there are various ways to achieve your desired outcome and the possibilities are vast, making it difficult to pinpoint a specific method. However, I believe this suggestion could be beneficial for you (although the extent of its usefulness may vary). In my example on Plunker, I am demonstrating the use of different stylesheets with unique attributes, as per your request. Your question has multiple potential solutions.

http://plnkr.co/edit/RaJgtc?p=preview

@Component({
  ...
  styleUrls: ['src/style.css','src/styleone.css'],
  ...
})

Answer №3

One recommendation is to start by following @Abdulrahman's method and if you encounter situations where more flexibility is needed because the styling requirements are not predetermined, consider utilizing the shadow-piercing CSS combinator >>>:

@Component({
  selector: 'box1-cmp',
  directives: [MyBox],
  template: `
    <my-box></my-box>
    <my-box></my-box>
    <my-box></my-box>`,
  styles: [`
    my-box >>> .column1 { width: 40%; }
    my-box >>> .column2 { width: 30%; }
    my-box >>> .column3 { width: 30%; }
  `]
})
export class Box1Cmp {
}
@Component({
  selector: 'box2-cmp',
  directives: [MyBox],
  template: `
    <my-box></my-box>
    <my-box></my-box>
    <my-box></my-box>`,
  styles: [`
    my-box >>> .column1 { width: 10%; }
    my-box >>> .column2 { width: 10%; }
    my-box >>> .column3 { width: 50%; }
  `]
})
export class Box2Cmp {
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Best Way to Calculate a Total Sum with Comma-Separated Values in AngularJS

In my application, I am utilizing the MEAN stack with AngularJS as the front-end. I am trying to figure out how to calculate the total sum and include comma values. I have managed to get the total sum value, but the comma value is not being calculated prop ...

Using conditional statements in CSS with the "if else"

Is it possible to use an if-else statement in CSS? This is the part where I would like to change the text color: <?php echo $status; ?> There are two statuses: Pending & Delivered. Pending should display in red and Delivered in green. Could I imp ...

Maximizing the use of default top positioning for absolutely positioned elements

After observing that an element with position:absolute can have its default top value determined based on its immediate parent's position, regardless of whether it is set to relative or not, BoltClock explained that in such cases, it remains in a stat ...

Modify MUI's ListItemText component by targeting a specific span to implement customized styles using the useStyle hook

It's quite perplexing that although this is a straightforward task in regular CSS, it must be accomplished through MUI's useStyles for some peculiar reason. Essentially, I possess a ListItem containing a ListItemText. It appears as follows: cons ...

Having trouble with less.modifyVars not functioning properly in Visual Studio?

I attempted to dynamically change the LESS variable using HTML within an AngularJS function. The code worked fine on XAMPP with simple HTML and CSS, but when I transferred it to an enterprise app in Visual Studio, it stopped functioning properly. While the ...

Arrangement of cards in a column

As someone who is new to working with CSS, Wordpress, and similar technologies, I am seeking assistance. I am struggling with creating card layouts. My goal is to achieve a layout similar to this, where the cards are displayed in two columns instead of ju ...

What is the best way to combine various ngrx selectors together?

I currently have 3 selectors in my index.ts file export const selectDetails = createSelector( // some code ); export const selectTransactionResponse = createSelector( // some code ); export const selectAdditionalDetails = createSelector( // some code ); ...

Ng-Zorro nz-range-picker resizing issue on smaller mobile screens

Currently using ng-zorro-antd 7.0.0 rc3 alongside angular 7.2.4. Encountering an issue where horizontal scrolling is not possible on mobile browsers when using the nz-range-picker. It appears that the element is too large for the screen, even though the p ...

What is the best way to create stylish corners on my website?

I'm struggling with creating a corner like the one shown in the image. As a beginner in frontend development, I attempted to write the following code but now I'm stuck. The Snippet: * { margin: 0; padding: 0; } body { height: 100vh; ...

Tips for aligning a menu that expands from the side to the center

I'm trying to center the menu on my webpage, but the issue is that it's stretching from the sides. Here's a sample image of the menu layout: I'm struggling to figure out how to fill the empty space on the left side of the menu. ...

Avoid having the navigation bar menu wrap over onto multiple lines

While using Bootstrap to create a navbar and resizing the browser window to a smaller width, you may notice that the menu items wrap onto multiple lines: How can we prevent the menu items from wrapping and keep them on a single line? (the buttons/search f ...

To retrieve the specific section containing data and prevent any empty sections in Angular2

My section is populated with static data, but I am also getting an empty section. Can someone assist me in retrieving only the data and excluding the empty section? TS: this.Emergencies = [{ "ContactName": "Person1", "Phone": "12345678", "Relati ...

Interacting between Angular 2/4 components via a shared service

Two components and one shared service are being used in the scenario: The parent component is responsible for displaying all companies, while the child component contains a removeCompany method. The issue arises when the removeCompany method is called fr ...

The <h> tag gains height on its own accord

Here is my original code: <h4 class="orange2" ><a href="<?php echo base_url();?>v/<?php echo $this->uri->segment(3);?>/<?php echo $v['uniq'];?>"><?php echo trim(strip_tags($v['video_name']));?> ...

Ways to display varied JSON information on a component in Angular 4

I am facing a challenge with a reusable component that fetches data from a JSON file. I want to customize the data displayed when this component is used as a subcomponent within other components. For example, let's say we have a Banana component: @U ...

What is the best way to display a single instance of a React component that is declared in multiple locations within the app?

Imagine I have 2 main components, A and B. Now, component C needs to be created inside both A and B. How can I guarantee that the same exact instance of C is generated in both places? Essentially, I want them to stay synchronized - any changes made to one ...

Encountering a problem with npm install due to git not being found

I recently updated my package JSON file with new dependencies and attempted to install npm, but encountered errors indicating that git could not be found: npm ERR! path git npm ERR! code ENOENT npm ERR! errno ENOENT npm ERR! syscall spawn git npm ...

Type 'function that accepts an argument of type User and TypedAction<"login start"> and returns void'

I recently started learning TypeScript and I'm delving into state management in Angular 11. However, when I try to create an effect, I encounter an error stating Argument of type '(action: User & TypedAction<"login start">) => void' ...

Retrieve information from Wordpress API and integrate it into Angular 7

I'm having an issue with pulling post data from Wordpress into my Angular 7 app. Even though I can see the data in the console, I'm unable to display it in my component. Any tips on how to resolve this? app.component.ts import { Component, OnIn ...

Difficulty in generating a canvas for capturing a signature using Angular 8

Currently, I am in the process of developing a component for signing using HTML 5 and canvas within Angular 8. My goal is for this component to be able to detect both touch events and mouse events. In my pursuit of creating this component, I have been dra ...