How to use @angular/compiler - 10 common examples

To help you get started, we’ve selected a few @angular/compiler examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github angular / angular / packages / compiler-cli / src / ngtsc / imports / src / emitter.ts View on Github external
emit(ref: Reference, context: ts.SourceFile, importMode: ImportMode): Expression|null {
    // If the emitter has specified ForceNewImport, then LocalIdentifierStrategy should not use a
    // local identifier at all, *except* in the source file where the node is actually declared.
    if (importMode === ImportMode.ForceNewImport &&
        getSourceFile(ref.node) !== getSourceFile(context)) {
      return null;
    }

    // A Reference can have multiple identities in different files, so it may already have an
    // Identifier in the requested context file.
    const identifier = ref.getIdentityIn(context);
    if (identifier !== null) {
      return new WrappedNodeExpr(identifier);
    } else {
      return null;
    }
  }
}
github johandb / svg-drawing-tool / node_modules / @angular / compiler / src / render3 / view / compiler.js View on Github external
var _b = parseNamedProperty(name_1), propertyName = _b.propertyName, unit = _b.unit;
                        styleBuilder.registerStyleInput(propertyName, binding.expression, unit, binding.sourceSpan);
                    }
                    else if (stylePrefix === 'class') {
                        styleBuilder.registerClassInput(parseNamedProperty(name_1).propertyName, binding.expression, binding.sourceSpan);
                    }
                    else {
                        // resolve literal arrays and literal objects
                        var value = binding.expression.visit(valueConverter);
                        var bindingExpr = bindingFn(bindingContext, value);
                        var _c = getBindingNameAndInstruction(binding), bindingName = _c.bindingName, instruction = _c.instruction, extraParams = _c.extraParams;
                        var instructionParams = [
                            elVarExp, o.literal(bindingName), o.importExpr(r3_identifiers_1.Identifiers.bind).callFn([bindingExpr.currValExpr])
                        ];
                        updateStatements.push.apply(updateStatements, tslib_1.__spread(bindingExpr.stmts));
                        updateStatements.push(o.importExpr(instruction).callFn(instructionParams.concat(extraParams)).toStmt());
                    }
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (bindings_1_1 && !bindings_1_1.done && (_a = bindings_1.return)) _a.call(bindings_1);
                }
                finally { if (e_3) throw e_3.error; }
            }
            if (styleBuilder.hasBindingsOrInitialValues()) {
                // since we're dealing with directives here and directives have a hostBinding
                // function, we need to generate special instructions that deal with styling
                // (both bindings and initial values). The instruction below will instruct
                // all initial styling (styling that is inside of a host binding within a
                // directive) to be attached to the host element of the directive.
github johandb / svg-drawing-tool / node_modules / @angular / compiler / src / render3 / view / compiler.js View on Github external
var name_1 = binding.name;
                    var stylePrefix = getStylingPrefix(name_1);
                    if (stylePrefix === 'style') {
                        var _b = parseNamedProperty(name_1), propertyName = _b.propertyName, unit = _b.unit;
                        styleBuilder.registerStyleInput(propertyName, binding.expression, unit, binding.sourceSpan);
                    }
                    else if (stylePrefix === 'class') {
                        styleBuilder.registerClassInput(parseNamedProperty(name_1).propertyName, binding.expression, binding.sourceSpan);
                    }
                    else {
                        // resolve literal arrays and literal objects
                        var value = binding.expression.visit(valueConverter);
                        var bindingExpr = bindingFn(bindingContext, value);
                        var _c = getBindingNameAndInstruction(binding), bindingName = _c.bindingName, instruction = _c.instruction, extraParams = _c.extraParams;
                        var instructionParams = [
                            elVarExp, o.literal(bindingName), o.importExpr(r3_identifiers_1.Identifiers.bind).callFn([bindingExpr.currValExpr])
                        ];
                        updateStatements.push.apply(updateStatements, tslib_1.__spread(bindingExpr.stmts));
                        updateStatements.push(o.importExpr(instruction).callFn(instructionParams.concat(extraParams)).toStmt());
                    }
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (bindings_1_1 && !bindings_1_1.done && (_a = bindings_1.return)) _a.call(bindings_1);
                }
                finally { if (e_3) throw e_3.error; }
            }
            if (styleBuilder.hasBindingsOrInitialValues()) {
                // since we're dealing with directives here and directives have a hostBinding
                // function, we need to generate special instructions that deal with styling
github angular / angular / packages / localize / src / tools / src / translate / translation_files / message_serialization / message_serializer.ts View on Github external
visitContainedNodes(nodes: Node[]): void {
    const length = nodes.length;
    let index = 0;
    while (index < length) {
      if (!this.isPlaceholderContainer(nodes[index])) {
        const startOfContainedNodes = index;
        while (index < length - 1) {
          index++;
          if (this.isPlaceholderContainer(nodes[index])) {
            break;
          }
        }
        if (index - startOfContainedNodes > 1) {
          // Only create a container if there are two or more contained Nodes in a row
          this.renderer.startContainer();
          visitAll(this, nodes.slice(startOfContainedNodes, index - 1));
          this.renderer.closeContainer();
        }
      }
      if (index < length) {
        nodes[index].visit(this, undefined);
      }
      index++;
    }
  }
github angular / angular / packages / language-service / src / utils.ts View on Github external
export function getPathToNodeAtPosition(nodes: Node[], position: number): HtmlAstPath {
  const path: Node[] = [];
  const visitor = new class extends RecursiveVisitor {
    visit(ast: Node) {
      const span = spanOf(ast);
      if (inSpan(position, span)) {
        path.push(ast);
      } else {
        // Returning a truthy value here will skip all children and terminate
        // the visit.
        return true;
      }
    }
  };
  visitAll(visitor, nodes);
  return new AstPath(path, position);
}
github johandb / svg-drawing-tool / node_modules / @angular / compiler-cli / src / perform_compile.js View on Github external
if (options.diagnostics) {
                var afterDiags = Date.now();
                allDiagnostics.push(util_1.createMessageDiagnostic("Time for diagnostics: " + (afterDiags - beforeDiags) + "ms."));
            }
            if (!hasErrors(allDiagnostics)) {
                emitResult =
                    program.emit({ emitCallback: emitCallback, mergeEmitResultsCallback: mergeEmitResultsCallback, customTransformers: customTransformers, emitFlags: emitFlags });
                allDiagnostics.push.apply(allDiagnostics, tslib_1.__spread(emitResult.diagnostics));
                return { diagnostics: allDiagnostics, program: program, emitResult: emitResult };
            }
            return { diagnostics: allDiagnostics, program: program };
        }
        catch (e) {
            var errMsg = void 0;
            var code = void 0;
            if (compiler_1.isSyntaxError(e)) {
                // don't report the stack for syntax errors as they are well known errors.
                errMsg = e.message;
                code = api.DEFAULT_ERROR_CODE;
            }
            else {
                errMsg = e.stack;
                // It is not a syntax error we might have a program with unknown state, discard it.
                program = undefined;
                code = api.UNKNOWN_ERROR_CODE;
            }
            allDiagnostics.push({ category: ts.DiagnosticCategory.Error, messageText: errMsg, code: code, source: api.SOURCE });
            return { diagnostics: allDiagnostics, program: program };
        }
    }
    exports.performCompilation = performCompilation;
github angular / compiler-builds / src / render3 / view / template.js View on Github external
function getLiteralFactory(constantPool, literal, allocateSlots) {
        var _a = constantPool.getLiteralFactory(literal), literalFactory = _a.literalFactory, literalFactoryArguments = _a.literalFactoryArguments;
        // Allocate 1 slot for the result plus 1 per argument
        var startSlot = allocateSlots(1 + literalFactoryArguments.length);
        literalFactoryArguments.length > 0 || util_1.error("Expected arguments to a literal factory function");
        var _b = pureFunctionCallInfo(literalFactoryArguments), identifier = _b.identifier, isVarLength = _b.isVarLength;
        // Literal factories are pure functions that only need to be re-invoked when the parameters
        // change.
        var args = [
            o.literal(startSlot),
            literalFactory,
        ];
        if (isVarLength) {
            args.push(o.literalArr(literalFactoryArguments));
        }
        else {
            args.push.apply(args, tslib_1.__spread(literalFactoryArguments));
        }
        return o.importExpr(identifier).callFn(args);
    }
    var BindingScope = /** @class */ (function () {
github angular / compiler-builds / src / render3 / view / styling_builder.js View on Github external
params: function (convertFn) {
                        // params => stylingProp(propName, value)
                        var params = [];
                        params.push(o.literal(input.name));
                        var convertResult = convertFn(value);
                        if (Array.isArray(convertResult)) {
                            params.push.apply(params, tslib_1.__spread(convertResult));
                        }
                        else {
                            params.push(convertResult);
                        }
                        if (allowUnits && input.unit) {
                            params.push(o.literal(input.unit));
                        }
                        return params;
                    }
                };
github angular / compiler-builds / src / render3 / r3_pipe_compiler.js View on Github external
definitionMapValues.push({ key: 'name', value: o.literal(pipe.name), quoted: false });
        // e.g. `type: MyPipe`
        definitionMapValues.push({ key: 'type', value: outputCtx.importExpr(pipe.type.reference), quoted: false });
        // e.g. `factory: function MyPipe_Factory() { return new MyPipe(); }`
        var deps = r3_factory_1.dependenciesFromGlobalMetadata(pipe.type, outputCtx, reflector);
        var templateFactory = r3_factory_1.compileFactoryFunction({
            name: compile_metadata_1.identifierName(pipe.type),
            fnOrClass: outputCtx.importExpr(pipe.type.reference), deps: deps,
            useNew: true,
            injectFn: r3_identifiers_1.Identifiers.directiveInject,
            useOptionalParam: false,
        });
        definitionMapValues.push({ key: 'factory', value: templateFactory, quoted: false });
        // e.g. `pure: true`
        if (pipe.pure) {
            definitionMapValues.push({ key: 'pure', value: o.literal(true), quoted: false });
        }
        var className = compile_metadata_1.identifierName(pipe.type);
        className || util_1.error("Cannot resolve the name of " + pipe.type);
        var definitionField = outputCtx.constantPool.propertyNameOf(3 /* Pipe */);
        var definitionFunction = o.importExpr(r3_identifiers_1.Identifiers.definePipe).callFn([o.literalMap(definitionMapValues)]);
        outputCtx.statements.push(new o.ClassStmt(
        /* name */ className, 
        /* parent */ null, 
        /* fields */ [new o.ClassField(
            /* name */ definitionField, 
            /* type */ o.INFERRED_TYPE, 
            /* modifiers */ [o.StmtModifier.Static], 
            /* initializer */ definitionFunction)], 
        /* getters */ [], 
        /* constructorMethod */ new o.ClassMethod(null, [], []), 
        /* methods */ []));
github angular / compiler-builds / src / render3 / view / styling_builder.js View on Github external
StylingBuilder.prototype.populateInitialStylingAttrs = function (attrs) {
            // [CLASS_MARKER, 'foo', 'bar', 'baz' ...]
            if (this._initialClassValues.length) {
                attrs.push(o.literal(1 /* Classes */));
                for (var i = 0; i < this._initialClassValues.length; i++) {
                    attrs.push(o.literal(this._initialClassValues[i]));
                }
            }
            // [STYLE_MARKER, 'width', '200px', 'height', '100px', ...]
            if (this._initialStyleValues.length) {
                attrs.push(o.literal(2 /* Styles */));
                for (var i = 0; i < this._initialStyleValues.length; i += 2) {
                    attrs.push(o.literal(this._initialStyleValues[i]), o.literal(this._initialStyleValues[i + 1]));
                }
            }
        };
        /**